OXYGENHUB
◆ identical-sides oxygen / crates / oxy-core / src / repo / tests.rs
415.8 KiB · Rust · last changed Identical conflict sides settle by themselves, keeping one, in any file (closes #146) 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
                identical: vec![],
274
                left: vec![]
275
            }]
276
        );
277
        let want: &[u8] = if reverse {
278
            b"a\nsecond\nfirst\nb\n"
279
        } else {
280
            b"a\nfirst\nsecond\nb\n"
281
        };
282
        assert_eq!(fs::read(root.join("f.txt")).unwrap(), want);
283
        let s = repo.snapshot("status").unwrap();
284
        assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
285
        let h = repo.commit("both", &[]).unwrap();
286
        assert_eq!(
287
            repo.store().get_change(&h).unwrap().kind,
288
            ChangeKind::Resolution
289
        );
290
        assert!(!repo.load_state(&[h]).unwrap().materialize().is_conflicted());
291
    }
292
}
293
294
/// oxygen#145: a file marked `merge=union` has its adjacent insertions
295
/// settled by the checkout itself, both kept, earliest first; the next
296
/// commit records the resolution. Other files keep their markers.
297
#[test]
298
fn union_files_keep_both_sides_on_checkout() {
299
    hermetic();
300
    let dir = tempfile::tempdir().unwrap();
301
    let root = dir.path();
302
    let repo = Repo::init(root).unwrap();
303
    write(root, ".oxyattributes", b"CHANGELOG.md merge=union\n");
304
    write(
305
        root,
306
        "CHANGELOG.md",
307
        b"# Changelog\n## Unreleased\n## 1.0\n",
308
    );
309
    write(root, "f.txt", b"a\nb\n");
310
    let h1 = repo.commit("base", &[]).unwrap();
311
    write(
312
        root,
313
        "CHANGELOG.md",
314
        b"# Changelog\n## Unreleased\n- one\n## 1.0\n",
315
    );
316
    write(root, "f.txt", b"a\none\nb\n");
317
    repo.commit("one", &[]).unwrap();
318
    repo.checkout(&[h1], false, "checkout").unwrap();
319
    write(
320
        root,
321
        "CHANGELOG.md",
322
        b"# Changelog\n## Unreleased\n- two\n## 1.0\n",
323
    );
324
    write(root, "f.txt", b"a\ntwo\nb\n");
325
    repo.commit("two", &[]).unwrap();
326
    let r = repo
327
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
328
        .unwrap();
329
    assert!(r.conflicted);
330
    assert_eq!(r.kept_both.len(), 1, "{:?}", r.kept_both);
331
    assert_eq!(r.kept_both[0].path, "CHANGELOG.md");
332
    assert_eq!(
333
        fs::read_to_string(root.join("CHANGELOG.md")).unwrap(),
334
        "# Changelog\n## Unreleased\n- one\n- two\n## 1.0\n"
335
    );
336
    assert!(has_conflict_markers(&fs::read(root.join("f.txt")).unwrap()));
337
    let s = repo.snapshot("status").unwrap();
338
    assert_eq!(
339
        statuses(&s),
340
        vec![("CHANGELOG.md".into(), ChangeStatus::Resolved)]
341
    );
342
}
343
344
/// oxygen#146: two bookmarks that resolved the same conflict to the same
345
/// text agree. Merged, their resolutions are a conflict whose sides are
346
/// identical: a checkout keeps one, in any file, and a host settles it so
347
/// too; the next commit records it.
348
#[test]
349
fn identical_resolutions_on_two_bookmarks_settle_by_themselves() {
350
    hermetic();
351
    let dir = tempfile::tempdir().unwrap();
352
    let root = dir.path();
353
    let repo = Repo::init(root).unwrap();
354
    write(root, "f.txt", b"a\nx\nb\n");
355
    let base = repo.commit("base", &[]).unwrap();
356
    write(root, "f.txt", b"a\nX1\nb\n");
357
    let c1 = repo.commit("X1", &[]).unwrap();
358
    repo.checkout(&[base], false, "checkout").unwrap();
359
    write(root, "f.txt", b"a\nX2\nb\n");
360
    let c2 = repo.commit("X2", &[]).unwrap();
361
    // Each bookmark merges both and resolves the conflict the same way.
362
    repo.checkout(&[c1, c2], false, "checkout").unwrap();
363
    assert!(has_conflict_markers(&fs::read(root.join("f.txt")).unwrap()));
364
    write(root, "f.txt", b"a\nX\nb\n");
365
    let r1 = repo.commit("resolve on one", &[]).unwrap();
366
    repo.checkout(&[c1, c2], false, "checkout").unwrap();
367
    write(root, "f.txt", b"a\nX\nb\n");
368
    let r2 = repo.commit("resolve on two", &[]).unwrap();
369
    assert_ne!(r1, r2);
370
371
    let st = repo.load_state(&[r1, r2]).unwrap();
372
    assert!(
373
        st.materialize().is_conflicted(),
374
        "two resolutions, one place"
375
    );
376
    assert_eq!(
377
        Repo::union_resolution(&st, &st.materialize()),
378
        Some(vec![("f.txt".into(), b"a\nX\nb\n".to_vec())]),
379
        "a host settles it"
380
    );
381
    let r = repo.checkout(&[r1, r2], false, "checkout").unwrap();
382
    assert!(r.conflicted);
383
    assert_eq!(r.kept_both.len(), 1, "{:?}", r.kept_both);
384
    assert_eq!(
385
        (r.kept_both[0].path.as_str(), &r.kept_both[0].identical),
386
        ("f.txt", &vec![1])
387
    );
388
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), "a\nX\nb\n");
389
    let s = repo.snapshot("status").unwrap();
390
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
391
    let merged = repo.commit("merge", &[]).unwrap();
392
    let st = repo.load_state(&[merged]).unwrap();
393
    assert!(!st.materialize().is_conflicted());
394
}
395
396
/// oxygen#145: a host (OxygenHub landing a proposal) settles a state whose
397
/// only conflicts are adjacent insertions in union files; any other
398
/// conflict needs a person.
399
#[test]
400
fn a_host_settles_a_state_whose_conflicts_are_all_union() {
401
    hermetic();
402
    let dir = tempfile::tempdir().unwrap();
403
    let root = dir.path();
404
    let repo = Repo::init(root).unwrap();
405
    write(root, ".oxyattributes", b"*.md merge=union\n");
406
    write(root, "A.md", b"a\nb\n");
407
    write(root, "B.md", b"x\ny\n");
408
    let h1 = repo.commit("base", &[]).unwrap();
409
    write(root, "A.md", b"a\none\nb\n");
410
    write(root, "B.md", b"x\nY1\n");
411
    let h2 = repo.commit("one", &[]).unwrap();
412
    repo.checkout(&[h1], false, "checkout").unwrap();
413
    write(root, "A.md", b"a\ntwo\nb\n");
414
    let h3 = repo.commit("two", &[]).unwrap();
415
    let st = repo.load_state(&[h2, h3]).unwrap();
416
    assert_eq!(
417
        Repo::union_resolution(&st, &st.materialize()),
418
        Some(vec![("A.md".into(), b"a\none\ntwo\nb\n".to_vec())])
419
    );
420
    // B.md's line replaced two ways: a person decides.
421
    repo.checkout(&[h3], false, "checkout").unwrap();
422
    write(root, "B.md", b"x\nY2\n");
423
    let h4 = repo.commit("Y2", &[]).unwrap();
424
    let st = repo.load_state(&[h2, h4]).unwrap();
425
    assert!(st.materialize().is_conflicted());
426
    assert_eq!(Repo::union_resolution(&st, &st.materialize()), None);
427
}
428
429
/// oxygen#121: two changes that each replaced the same line are not an
430
/// adjacent insertion: keeping both would keep two versions of the line,
431
/// so `--both` leaves the markers, as it does for markers already edited.
432
#[test]
433
fn keeping_both_refuses_replaced_or_edited_lines() {
434
    hermetic();
435
    let (dir, repo, _, _, _) = conflicted_repo();
436
    let root = dir.path();
437
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
438
        .unwrap();
439
    let marked = fs::read(root.join("f.txt")).unwrap();
440
    let snap = repo.snapshot("status").unwrap();
441
    let node = snap.base_snapshot.files["f.txt"].node;
442
    assert_eq!(snap.base.both_sides(&node), vec![None]);
443
    let kept = repo.keep_both(&snap, &["f.txt".into()], false).unwrap();
444
    assert!(kept[0].settled.is_empty());
445
    assert_eq!(kept[0].left[0].0, 1);
446
    assert!(kept[0].left[0].1.contains("both sides changed"), "{kept:?}");
447
    assert_eq!(fs::read(root.join("f.txt")).unwrap(), marked);
448
449
    // An adjacent insertion whose lines were edited between the markers.
450
    let sides = vec![Some(vec![b"x\n".to_vec(), b"y\n".to_vec()])];
451
    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";
452
    let (out, settled, left) = super::snapshot::keep_both_text(text, &sides, false);
453
    assert_eq!(out, text.to_vec());
454
    assert!(settled.is_empty());
455
    assert!(left[0].1.contains("edited"), "{left:?}");
456
    // Unedited, in either order on disk: kept in the graph's order.
457
    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";
458
    let (out, settled, _) = super::snapshot::keep_both_text(text, &sides, false);
459
    assert_eq!(out, b"a\nx\ny\nb\n".to_vec());
460
    assert_eq!(settled, vec![1]);
461
}
462
463
#[test]
464
fn concurrent_edits_conflict_and_can_be_resolved() {
465
    hermetic();
466
    let (dir, repo, h1, h2, h3) = conflicted_repo();
467
    let root = dir.path();
468
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
469
    assert_eq!(heads, [h2, h3].into_iter().collect());
470
    let st = repo.load_state(&[h2, h3]).unwrap();
471
    assert!(st.materialize().is_conflicted());
472
473
    // Checking out main writes markers.
474
    let r = repo
475
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
476
        .unwrap();
477
    assert!(r.conflicted);
478
    let marked = fs::read_to_string(root.join("f.txt")).unwrap();
479
    assert!(
480
        marked.starts_with("a\n<<<<<<< oxy conflict 1 of 1"),
481
        "{marked}"
482
    );
483
    assert!(
484
        marked.contains("B\n") && marked.contains("X\n") && marked.ends_with("end\nc\n"),
485
        "{marked}"
486
    );
487
    assert!(has_conflict_markers(marked.as_bytes()));
488
    // Untouched markers: clean working copy; commit has nothing to do.
489
    let s = repo.snapshot("status").unwrap();
490
    assert!(s.statuses.is_empty());
491
    assert!(!s.resolves);
492
493
    // Partially edited file that still has markers cannot be committed.
494
    write(root, "f.txt", marked.replace("B\n", "BB\n").as_bytes());
495
    let s = repo.snapshot("status").unwrap();
496
    assert_eq!(
497
        statuses(&s),
498
        vec![("f.txt".into(), ChangeStatus::ConflictEdited)]
499
    );
500
    assert!(repo.commit("no", &[]).is_err());
501
502
    // Resolve by keeping one side and adding a line elsewhere.
503
    write(root, "f.txt", b"a\nX\nc\nd\n");
504
    let s = repo.snapshot("status").unwrap();
505
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
506
    assert!(s.resolves);
507
    let h4 = repo.commit("resolve", &[]).unwrap();
508
    let c4 = repo.store().get_change(&h4).unwrap();
509
    assert_eq!(c4.kind, ChangeKind::Resolution);
510
    let mut want = vec![h1, h2, h3];
511
    want.sort();
512
    assert_eq!(
513
        c4.deps, want,
514
        "a resolution depends on exactly the contributors and what it references"
515
    );
516
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h4]);
517
    let snap = repo.load_state(&[h4]).unwrap().materialize();
518
    assert!(!snap.is_conflicted());
519
    assert!(
520
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
521
    );
522
    assert!(!repo.snapshot("status").unwrap().changed);
523
    // A peer holding only h2 and h3 and receiving h4 sees the same result,
524
    // whatever order the changes arrive in.
525
    let mut st = State::new();
526
    for h in [h4, h3, h1, h2] {
527
        st.add_unchecked(repo.store().get_change(&h).unwrap());
528
    }
529
    st.validate().unwrap();
530
    assert!(
531
        matches!(&st.materialize().files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
532
    );
533
}
534
535
/// oxygen#118 (Metal Gear): a resolution commits by paths, leaving other
536
/// work uncommitted, so long as it takes every file it resolves; and
537
/// `amend PATHS` folds only those paths into the head.
538
#[test]
539
fn resolutions_and_amends_take_paths() {
540
    hermetic();
541
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
542
    let root = dir.path();
543
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
544
        .unwrap();
545
    // The conflict resolved, and other work beside it.
546
    write(root, "f.txt", b"a\nX\nc\n");
547
    write(root, "notes.txt", b"pending\n");
548
    let s = repo.snapshot("status").unwrap();
549
    assert!(s.resolves);
550
    let err = repo
551
        .commit_selection_partial("resolve", &[], &Selection::Paths(vec!["notes.txt".into()]))
552
        .unwrap_err()
553
        .to_string();
554
    assert!(
555
        err.contains("takes every file it resolves") && err.contains("f.txt"),
556
        "{err}"
557
    );
558
    let (h4, partial) = repo
559
        .commit_selection_partial("resolve", &[], &Selection::Paths(vec!["f.txt".into()]))
560
        .unwrap();
561
    assert!(partial);
562
    assert_eq!(
563
        repo.store().get_change(&h4).unwrap().kind,
564
        ChangeKind::Resolution
565
    );
566
    assert!(!repo
567
        .load_state(&[h4])
568
        .unwrap()
569
        .materialize()
570
        .is_conflicted());
571
    let s = repo.snapshot("status").unwrap();
572
    assert_eq!(
573
        statuses(&s),
574
        vec![("notes.txt".into(), ChangeStatus::Added)],
575
        "the other work waits"
576
    );
577
578
    // amend PATHS: only those paths join the head; it keeps its ChangeId.
579
    // On the resolution, so the bookmark has one head to amend.
580
    let h5 = repo.commit("notes", &[h4]).unwrap();
581
    let id5 = repo.store().get_change(&h5).unwrap().change_id;
582
    write(root, "notes.txt", b"pending\nmore\n");
583
    write(root, "other.txt", b"later\n");
584
    let h6 = repo
585
        .amend_paths(Some("notes, amended"), &["notes.txt".into()])
586
        .unwrap();
587
    let c6 = repo.store().get_change(&h6).unwrap();
588
    assert_eq!((c6.change_id, c6.message.as_str()), (id5, "notes, amended"));
589
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h6]);
590
    let snap6 = repo.load_state(&[h6]).unwrap().materialize();
591
    assert!(
592
        matches!(&snap6.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"pending\nmore\n")
593
    );
594
    assert!(
595
        !snap6.files.contains_key("other.txt"),
596
        "other.txt stays out"
597
    );
598
    let s = repo.snapshot("status").unwrap();
599
    assert_eq!(
600
        statuses(&s),
601
        vec![("other.txt".into(), ChangeStatus::Added)]
602
    );
603
}
604
605
#[test]
606
fn resolution_may_keep_both_sides_or_neither() {
607
    hermetic();
608
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
609
    let root = dir.path();
610
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
611
        .unwrap();
612
    // Keep both sides in a chosen order.
613
    write(root, "f.txt", b"a\nX\nB\nc\n");
614
    let h = repo.commit("both", &[]).unwrap();
615
    let snap = repo.load_state(&[h]).unwrap().materialize();
616
    assert!(!snap.is_conflicted());
617
    assert!(
618
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n")
619
    );
620
    // Undo and instead drop the whole region.
621
    repo.undo().unwrap();
622
    write(root, "f.txt", b"a\nc\n");
623
    let h = repo.commit("neither", &[]).unwrap();
624
    let snap = repo.load_state(&[h]).unwrap().materialize();
625
    assert!(!snap.is_conflicted());
626
    assert!(
627
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n")
628
    );
629
}
630
631
#[test]
632
fn name_conflict_resolved_by_removing_a_candidate() {
633
    hermetic();
634
    let dir = tempfile::tempdir().unwrap();
635
    let root = dir.path();
636
    let repo = Repo::init(root).unwrap();
637
    write(root, "keep.txt", b"k\n");
638
    let h1 = repo.commit("base", &[]).unwrap();
639
    write(root, "new.txt", b"one\n");
640
    repo.commit("one", &[]).unwrap();
641
    repo.checkout(&[h1], false, "checkout").unwrap();
642
    write(root, "new.txt", b"two\n");
643
    repo.commit("two", &[]).unwrap();
644
    let r = repo
645
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
646
        .unwrap();
647
    assert!(r.conflicted);
648
    assert!(
649
        root.join("new.txt.oxy-conflict-1").exists()
650
            && root.join("new.txt.oxy-conflict-2").exists()
651
    );
652
    assert!(!root.join("new.txt").exists());
653
    // Candidate numbering follows change-hash order, so pick by content:
654
    // keep the "two" candidate under the real name and drop the other.
655
    let (keep, drop) = if fs::read(root.join("new.txt.oxy-conflict-1")).unwrap() == b"two\n" {
656
        (1, 2)
657
    } else {
658
        (2, 1)
659
    };
660
    fs::remove_file(root.join(format!("new.txt.oxy-conflict-{drop}"))).unwrap();
661
    fs::rename(
662
        root.join(format!("new.txt.oxy-conflict-{keep}")),
663
        root.join("new.txt"),
664
    )
665
    .unwrap();
666
    let h = repo.commit("pick two", &[]).unwrap();
667
    assert_eq!(
668
        repo.store().get_change(&h).unwrap().kind,
669
        ChangeKind::Resolution
670
    );
671
    // The resolution does not touch keep.txt, so it does not depend on h1;
672
    // the bookmark keeps both as heads and their union is the state.
673
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
674
    assert_eq!(heads, [h1, h].into_iter().collect());
675
    let snap = repo
676
        .load_state(&repo.bookmark_heads().unwrap())
677
        .unwrap()
678
        .materialize();
679
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
680
    assert_eq!(
681
        snap.files.keys().cloned().collect::<Vec<_>>(),
682
        ["keep.txt", "new.txt"]
683
    );
684
    assert!(
685
        matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n")
686
    );
687
}
688
689
/// Each of two bookmarks adds `path` (a file written by `side` on each)
690
/// from the same base, and the second is merged into the first. Returns
691
/// the repository on `main`, the merge's heads, and the three changes.
692
fn merged_additions(
693
    side: impl Fn(&Path, bool),
694
) -> (tempfile::TempDir, Repo, Vec<ChangeHash>, [ChangeHash; 3]) {
695
    let dir = tempfile::tempdir().unwrap();
696
    let root = dir.path().to_path_buf();
697
    let mut repo = Repo::init(&root).unwrap();
698
    write(&root, "keep.txt", b"k\n");
699
    let h1 = repo.commit("base", &[]).unwrap();
700
    repo.bookmark_create("side", None).unwrap();
701
    side(&root, false);
702
    let ha = repo.commit("add on main", &[]).unwrap();
703
    repo.bookmark_switch("side", false).unwrap();
704
    side(&root, true);
705
    let hb = repo.commit("add on side", &[]).unwrap();
706
    repo.bookmark_switch("main", false).unwrap();
707
    let m = repo.merge("side").unwrap();
708
    assert!(m.changed && m.checked_out);
709
    (dir, repo, m.heads, [h1, ha, hb])
710
}
711
712
fn conflict_copies(root: &Path) -> Vec<String> {
713
    let mut out: Vec<String> = fs::read_dir(root)
714
        .unwrap()
715
        .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
716
        .filter(|n| n.contains(".oxy-conflict-"))
717
        .collect();
718
    out.sort();
719
    out
720
}
721
722
/// The same path added on two bookmarks with identical content is one
723
/// file after the merge (oxygen#101): no conflict, nothing to resolve,
724
/// nothing recorded; and editing or removing it later keeps it one.
725
#[test]
726
fn identical_additions_unify_on_merge() {
727
    hermetic();
728
    let (dir, repo, heads, [h1, ha, hb]) =
729
        merged_additions(|root, _| write(root, "x.txt", b"same\nlines\n"));
730
    let root = dir.path();
731
    // The tree graph has the name conflict; every reader sees one file.
732
    let st = repo.load_state(&heads).unwrap();
733
    assert!(st
734
        .tree()
735
        .view()
736
        .conflicts
737
        .iter()
738
        .any(|c| matches!(c, crate::tree::TreeConflict::Name { .. })));
739
    let snap = st.materialize();
740
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
741
    assert_eq!(
742
        snap.files.keys().cloned().collect::<Vec<_>>(),
743
        ["keep.txt", "x.txt"]
744
    );
745
    assert!(
746
        matches!(&snap.files["x.txt"].content, FileContent::Text { bytes, .. } if bytes == b"same\nlines\n")
747
    );
748
    assert_eq!(snap.tree.unified.len(), 1);
749
    // On disk once, the working copy clean, nothing to commit.
750
    assert_eq!(fs::read(root.join("x.txt")).unwrap(), b"same\nlines\n");
751
    assert!(
752
        conflict_copies(root).is_empty(),
753
        "{:?}",
754
        conflict_copies(root)
755
    );
756
    let s = repo.snapshot("status").unwrap();
757
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
758
    assert!(!s.changed && !s.resolves);
759
    assert!(!s.base_snapshot.is_conflicted());
760
    assert!(s.wc.tree_ops.is_empty() && s.wc.edits.is_empty());
761
    let json = repo.status_json(&s).unwrap();
762
    assert!(json.contains("\"conflicted\":false"), "{json}");
763
    assert!(repo.commit("nothing", &[]).is_err());
764
    assert_eq!(repo.file_at("x.txt", None).unwrap(), b"same\nlines\n");
765
    // A peer holding the same changes, added in another order, agrees.
766
    let mut peer = State::new();
767
    for h in [hb, ha, h1] {
768
        peer.add_unchecked(repo.store().get_change(&h).unwrap());
769
    }
770
    peer.validate().unwrap();
771
    let ps = peer.materialize();
772
    assert!(!ps.is_conflicted());
773
    assert_eq!(ps.tree.entries["x.txt"], snap.tree.entries["x.txt"]);
774
    assert_eq!(ps.tree.unified, snap.tree.unified);
775
    // The file's history is both additions.
776
    let log: Vec<ChangeHash> = repo
777
        .log_for_path("x.txt")
778
        .unwrap()
779
        .iter()
780
        .map(|e| e.hash)
781
        .collect();
782
    assert!(log.contains(&ha) && log.contains(&hb), "{log:?}");
783
784
    // Edited and committed: one file still, the duplicate retired with it.
785
    write(root, "x.txt", b"same\nedited\n");
786
    let s = repo.snapshot("status").unwrap();
787
    assert_eq!(statuses(&s), vec![("x.txt".into(), ChangeStatus::Modified)]);
788
    let he = repo.commit("edit x", &[]).unwrap();
789
    let c = repo.store().get_change(&he).unwrap();
790
    assert_eq!(c.kind, ChangeKind::Normal);
791
    let (dup, _) = snap.tree.unified.iter().next().unwrap();
792
    assert!(
793
        c.tree_ops
794
            .iter()
795
            .any(|o| matches!(o, TreeOp::RemoveNode { node, .. } if node == dup)),
796
        "{:?}",
797
        c.tree_ops
798
    );
799
    let d = repo.describe_change(&he).unwrap();
800
    assert!(!d.contains("D x.txt"), "{d}");
801
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
802
    assert!(
803
        st.tree().view().conflicts.is_empty(),
804
        "nothing left to unify"
805
    );
806
    let snap = st.materialize();
807
    assert!(!snap.is_conflicted());
808
    assert!(
809
        matches!(&snap.files["x.txt"].content, FileContent::Text { bytes, .. } if bytes == b"same\nedited\n")
810
    );
811
    assert!(!repo.snapshot("status").unwrap().changed);
812
813
    // Removed and committed: gone.
814
    fs::remove_file(root.join("x.txt")).unwrap();
815
    repo.commit("drop x", &[]).unwrap();
816
    let snap = repo
817
        .load_state(&repo.bookmark_heads().unwrap())
818
        .unwrap()
819
        .materialize();
820
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
821
    assert_eq!(snap.files.keys().cloned().collect::<Vec<_>>(), ["keep.txt"]);
822
    assert!(!root.join("x.txt").exists());
823
}
824
825
/// Removing, renaming, or committing just the path of a unified file
826
/// retires its duplicate with it, so the conflict never comes back.
827
#[test]
828
fn unified_additions_stay_one_when_removed_renamed_or_committed_alone() {
829
    hermetic();
830
    let add = |root: &Path, _: bool| write(root, "x.txt", b"same\n");
831
    for how in ["remove", "rename", "path", "hunk"] {
832
        let (dir, repo, _, _) = merged_additions(add);
833
        let root = dir.path();
834
        match how {
835
            "remove" => fs::remove_file(root.join("x.txt")).unwrap(),
836
            "rename" => fs::rename(root.join("x.txt"), root.join("y.txt")).unwrap(),
837
            _ => {
838
                write(root, "x.txt", b"same\nmore\n");
839
                write(root, "other.txt", b"o\n");
840
            }
841
        }
842
        let s = repo.snapshot("status").unwrap();
843
        let h = match how {
844
            "path" => repo
845
                .commit_selection("x alone", &[], &Selection::Paths(vec!["x.txt".into()]))
846
                .unwrap(),
847
            "hunk" => {
848
                let (_, hunks) = repo.hunks().unwrap();
849
                // The duplicate's retirement is no hunk of its own.
850
                assert!(hunks.iter().all(|h| !h.text.starts_with("D ")), "{hunks:?}");
851
                let x: Vec<usize> = hunks
852
                    .iter()
853
                    .filter(|h| h.path == "x.txt")
854
                    .map(|h| h.index)
855
                    .collect();
856
                assert!(!x.is_empty());
857
                repo.commit_selection("x hunks", &[], &Selection::Hunks(x))
858
                    .unwrap()
859
            }
860
            _ => repo.commit(how, &[]).unwrap(),
861
        };
862
        assert!(!s.base_snapshot.is_conflicted());
863
        let heads = repo.bookmark_heads().unwrap();
864
        assert!(heads.contains(&h));
865
        let snap = repo.load_state(&heads).unwrap().materialize();
866
        assert!(!snap.is_conflicted(), "{how}: {:?}", snap.tree.conflicts);
867
        let want: &[&str] = match how {
868
            "remove" => &["keep.txt"],
869
            "rename" => &["keep.txt", "y.txt"],
870
            _ => &["keep.txt", "x.txt"],
871
        };
872
        assert_eq!(
873
            snap.files.keys().cloned().collect::<Vec<_>>(),
874
            want,
875
            "{how}"
876
        );
877
        assert!(conflict_copies(root).is_empty(), "{how}");
878
    }
879
}
880
881
/// The same path added with different content, or a different mode, is a
882
/// name conflict as before.
883
#[test]
884
fn additions_that_differ_still_conflict() {
885
    hermetic();
886
    #[cfg(unix)]
887
    use std::os::unix::fs::PermissionsExt;
888
    let content =
889
        |root: &Path, side: bool| write(root, "x.txt", if side { b"two\n" } else { b"one\n" });
890
    let mode = |root: &Path, side: bool| {
891
        write(root, "x.txt", b"same\n");
892
        #[cfg(unix)]
893
        if side {
894
            fs::set_permissions(root.join("x.txt"), fs::Permissions::from_mode(0o755)).unwrap();
895
        }
896
    };
897
    let check = |what: &str, side: &dyn Fn(&Path, bool)| {
898
        let (dir, repo, heads, _) = merged_additions(side);
899
        let snap = repo.load_state(&heads).unwrap().materialize();
900
        assert!(snap.tree.unified.is_empty(), "{what}");
901
        assert!(
902
            snap.tree.conflicts.iter().any(
903
                |c| matches!(c, crate::tree::TreeConflict::Name { name, .. } if name == "x.txt")
904
            ),
905
            "{what}: {:?}",
906
            snap.tree.conflicts
907
        );
908
        assert_eq!(
909
            conflict_copies(dir.path()),
910
            ["x.txt.oxy-conflict-1", "x.txt.oxy-conflict-2"],
911
            "{what}"
912
        );
913
        assert!(!dir.path().join("x.txt").exists(), "{what}");
914
    };
915
    check("content", &content);
916
    #[cfg(unix)]
917
    check("mode", &mode);
918
    #[cfg(not(unix))]
919
    let _ = mode;
920
}
921
922
/// The same subrepo at the same pin, added on two bookmarks, is one
923
/// subrepo after the merge (oxygen#101), as is the identical
924
/// `.oxymodules` beside it.
925
#[test]
926
fn the_same_subrepo_added_on_two_bookmarks_unifies() {
927
    hermetic();
928
    let dir = tempfile::tempdir().unwrap();
929
    let root = dir.path();
930
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
931
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
932
    let lib = Repo::clone(&lib_url, &root.join("lib"))
933
        .unwrap()
934
        .with_home(root.join("home"));
935
    write(&root.join("lib"), "lib.txt", b"v1\n");
936
    lib.commit("lib v1", &[]).unwrap();
937
    assert!(lib.push("origin", false).unwrap()[0].ok);
938
    let _ = lib_origin;
939
940
    let app_dir = root.join("app");
941
    let mut app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
942
    write(&app_dir, "main.txt", b"app\n");
943
    app.commit("base", &[]).unwrap();
944
    app.bookmark_create("side", None).unwrap();
945
    app.submodule_add(&lib_url, "rstar-api", None).unwrap();
946
    let modules = fs::read(app_dir.join(".oxymodules")).unwrap();
947
    app.commit("rstar-api on main", &[]).unwrap();
948
    // On the other bookmark the nested repository is still there (it is
949
    // never deleted); registering it again adds it at the same pin.
950
    app.bookmark_switch("side", false).unwrap();
951
    assert!(app_dir.join("rstar-api/.oxy").is_dir());
952
    write(&app_dir, ".oxymodules", &modules);
953
    let s = app.snapshot("status").unwrap();
954
    assert_eq!(
955
        statuses(&s),
956
        vec![
957
            (".oxymodules".into(), ChangeStatus::Added),
958
            ("rstar-api".into(), ChangeStatus::Added)
959
        ]
960
    );
961
    app.commit("rstar-api on side", &[]).unwrap();
962
    app.bookmark_switch("main", false).unwrap();
963
964
    let m = app.merge("side").unwrap();
965
    assert!(m.changed && m.checked_out);
966
    let snap = app.load_state(&m.heads).unwrap().materialize();
967
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
968
    assert_eq!(snap.tree.unified.len(), 2);
969
    assert_eq!(snap.files["rstar-api"].kind, NodeKind::Subrepo);
970
    assert!(conflict_copies(&app_dir).is_empty());
971
    let s = app.snapshot("status").unwrap();
972
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
973
    assert!(!s.base_snapshot.is_conflicted());
974
    assert_eq!(
975
        fs::read_to_string(app_dir.join("rstar-api/lib.txt")).unwrap(),
976
        "v1\n"
977
    );
978
}
979
980
#[test]
981
fn identities_and_signed_commits() {
982
    hermetic();
983
    let dir = tempfile::tempdir().unwrap();
984
    let root = dir.path();
985
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
986
    write(root, "a.txt", b"a\n");
987
    let h0 = repo.commit("unsigned", &[]).unwrap();
988
    assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
989
    assert_eq!(
990
        repo.store().get_change(&h0).unwrap().author,
991
        ObjectRef::ZERO
992
    );
993
994
    let (key, id) = repo
995
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
996
        .unwrap();
997
    assert_eq!(id.hash(), key);
998
    assert_eq!(repo.config.author_key, Some(key));
999
    // Config survives reopen; the secret key is found again.
1000
    let reopened = Repo::open(root).unwrap().with_home(root.join("home"));
1001
    assert_eq!(reopened.config.author_key, Some(key));
1002
    assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
1003
1004
    // Default core.sign = seal: commits carry the author but no signature.
1005
    write(root, "a.txt", b"a\nb\n");
1006
    let h1 = repo.commit("authored", &[]).unwrap();
1007
    assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
1008
    assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
1009
    // Signing later works too.
1010
    repo.sign_change(&h1).unwrap();
1011
    assert!(
1012
        matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
1013
    );
1014
1015
    repo.config.set("core.sign", "change").unwrap();
1016
    repo.save_config().unwrap();
1017
    write(root, "a.txt", b"a\nb\nc\n");
1018
    let h2 = repo.commit("signed", &[]).unwrap();
1019
    assert_eq!(
1020
        repo.verify_change(&h2).unwrap(),
1021
        SignatureStatus::Valid {
1022
            key,
1023
            name: "Ada".into(),
1024
            email: "[email protected]".into(),
1025
            sealed: false,
1026
            revoked: false
1027
        }
1028
    );
1029
1030
    // A signature by a key that is not the author or a delegate is rejected
1031
    // when the change names an author; an anonymous change (made before any
1032
    // identity, author zero) is adopted by whoever signs it (spec §14.4).
1033
    let other = SecretKey::generate();
1034
    let other_id = other.identity("Mallory", "[email protected]", 0);
1035
    let other_key = repo.store().put_identity(&other_id).unwrap();
1036
    write(root, "a.txt", b"a\nb\nc\nd\n");
1037
    repo.config.set("core.sign", "seal").unwrap();
1038
    let h3 = repo.commit("ada's, unsigned", &[]).unwrap();
1039
    let forged = other.sign(Domain::Change, &other_key, &h3);
1040
    repo.store().put_signature(&h3, &forged).unwrap();
1041
    assert!(
1042
        matches!(repo.verify_change(&h3).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author"))
1043
    );
1044
    let adopted = other.sign(Domain::Change, &other_key, &h0);
1045
    repo.store().put_signature(&h0, &adopted).unwrap();
1046
    assert!(
1047
        matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Valid { name, .. } if name == "Mallory")
1048
    );
1049
1050
    // Tampering with the stored signature invalidates it.
1051
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
1052
    sig.ed[0] ^= 1;
1053
    repo.store().put_signature(&h2, &sig).unwrap();
1054
    assert!(matches!(
1055
        repo.verify_change(&h2).unwrap(),
1056
        SignatureStatus::Invalid(_)
1057
    ));
1058
1059
    // Without the secret key, signing at commit fails cleanly.
1060
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
1061
    write(root, "a.txt", b"z\n");
1062
    assert!(no_keys.commit("cannot sign", &[]).is_err());
1063
}
1064
1065
#[test]
1066
fn checkout_moves_the_working_copy() {
1067
    hermetic();
1068
    let dir = tempfile::tempdir().unwrap();
1069
    let root = dir.path();
1070
    let repo = Repo::init(root).unwrap();
1071
    write(root, "a.txt", b"one\n");
1072
    write(root, "sub/deep/b.txt", b"b\n");
1073
    let h1 = repo.commit("first", &[]).unwrap();
1074
    write(root, "a.txt", b"two\n");
1075
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
1076
    write(root, "bin.dat", &[0, 1, 2, 3]);
1077
    let h2 = repo.commit("second", &[]).unwrap();
1078
1079
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
1080
    assert_eq!(
1081
        r,
1082
        CheckoutReport {
1083
            written: 2,
1084
            removed: 1,
1085
            removed_paths: vec!["bin.dat".into()],
1086
            conflicted: false,
1087
            notes: vec![],
1088
            lacks: 1,
1089
            kept_both: vec![],
1090
        }
1091
    );
1092
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1093
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
1094
    assert!(!root.join("bin.dat").exists());
1095
    let (_, wc) = repo.working_copy().unwrap();
1096
    assert_eq!(wc.deps, vec![h1]);
1097
    assert!(
1098
        !repo.snapshot("status").unwrap().changed,
1099
        "checkout leaves a clean working copy"
1100
    );
1101
    // The bookmark still points at h2.
1102
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
1103
1104
    // Dirty working copy refuses without --discard.
1105
    write(root, "a.txt", b"dirty\n");
1106
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
1107
    let r = repo
1108
        .checkout(&[h2], true, "oxy checkout --discard")
1109
        .unwrap();
1110
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
1111
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
1112
    assert!(!root.join("sub").exists(), "empty directories are pruned");
1113
    assert_eq!(r.removed, 1);
1114
    assert!(!repo.snapshot("status").unwrap().changed);
1115
1116
    // Refuses to write through a symlinked directory.
1117
    #[cfg(unix)]
1118
    {
1119
        fs::remove_dir_all(root.join("sub")).ok();
1120
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
1121
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
1122
    }
1123
}
1124
1125
#[test]
1126
fn large_files_are_chunked_and_read_back() {
1127
    hermetic();
1128
    let dir = tempfile::tempdir().unwrap();
1129
    let repo = Repo::init(dir.path()).unwrap();
1130
    let mut big = vec![0u8; 700 * 1024];
1131
    for (i, b) in big.iter_mut().enumerate() {
1132
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
1133
    }
1134
    let r = repo.store_blob(&big).unwrap();
1135
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
1136
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
1137
    assert_eq!(repo.read_blob(&r).unwrap(), big);
1138
    assert_eq!(Repo::blob_ref(&big), r);
1139
}
1140
1141
#[test]
1142
fn clone_push_pull_with_seals_and_attestations() {
1143
    hermetic();
1144
    let dir = tempfile::tempdir().unwrap();
1145
    let root = dir.path();
1146
    let origin_path = root.join("origin");
1147
    let origin = Repo::init(&origin_path).unwrap();
1148
    let origin_url = origin_path.to_string_lossy().to_string();
1149
1150
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
1151
    let mut a = Repo::clone(&origin_url, &root.join("a"))
1152
        .unwrap()
1153
        .with_home(root.join("home-a"));
1154
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
1155
    let (key_a, _) = a
1156
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
1157
        .unwrap();
1158
    write(&root.join("a"), "f.txt", b"a\n");
1159
    let h1 = a.commit("first", &[]).unwrap();
1160
    let results = a.push("origin", false).unwrap();
1161
    origin.refresh().unwrap();
1162
    assert!(results[0].ok, "{}", results[0].reason);
1163
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
1164
    // The change was sealed at push and the reference attested.
1165
    assert!(
1166
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
1167
    );
1168
    assert_eq!(
1169
        origin.verify_change(&h1).unwrap(),
1170
        SignatureStatus::Unsigned
1171
    );
1172
    let serial_of = |att: &SignedAttest| match att.attest.body {
1173
        AttestBody::Ref { serial, .. } => serial,
1174
        _ => unreachable!(),
1175
    };
1176
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
1177
    // A bookmark new to the remote starts at the clock (past any deleted
1178
    // namesake's serial); later updates count up from there.
1179
    let first = serial_of(&att);
1180
    assert!(first > 1_000_000_000_000, "{first}");
1181
    let again = a.push("origin", false).unwrap();
1182
    origin.refresh().unwrap();
1183
    assert!(again[0].ok && again[0].reason.contains("up to date"));
1184
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
1185
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
1186
1187
    // B clones and sees the file and the seal.
1188
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
1189
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
1190
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
1191
    assert!(matches!(
1192
        b.authenticate_change(&h1).unwrap(),
1193
        SignatureStatus::Valid { sealed: true, .. }
1194
    ));
1195
1196
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
1197
    write(&root.join("b"), "f.txt", b"a\nb\n");
1198
    let h2 = b.commit("second", &[]).unwrap();
1199
    assert!(b.push("origin", false).unwrap()[0].ok);
1200
    origin.refresh().unwrap();
1201
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
1202
1203
    // A commits an independent change; push is refused until A pulls.
1204
    write(&root.join("a"), "g.txt", b"g\n");
1205
    let h3 = a.commit("third", &[]).unwrap();
1206
    assert!(a.push("origin", false).is_err());
1207
    let pr = a.pull("origin").unwrap();
1208
    assert!(pr.changed && pr.checked_out);
1209
    let mut want = vec![h2, h3];
1210
    want.sort();
1211
    assert_eq!(pr.heads, want);
1212
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
1213
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
1214
    let results = a.push("origin", false).unwrap();
1215
    origin.refresh().unwrap();
1216
    assert!(results[0].ok, "{}", results[0].reason);
1217
    let mut origin_heads = origin.bookmark_heads().unwrap();
1218
    origin_heads.sort();
1219
    assert_eq!(origin_heads, want);
1220
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
1221
    assert_eq!(serial_of(&att), first + 1);
1222
1223
    // B pulls and ends up identical.
1224
    let pr = b.pull("origin").unwrap();
1225
    assert_eq!(pr.heads, want);
1226
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
1227
    assert!(!b.snapshot("status").unwrap().changed);
1228
1229
    // Concurrent edits of the same line: the union is a reified conflict.
1230
    write(&root.join("a"), "f.txt", b"a\nA\n");
1231
    a.commit("a-edit", &[]).unwrap();
1232
    a.push("origin", false).unwrap();
1233
    origin.refresh().unwrap();
1234
    write(&root.join("b"), "f.txt", b"a\nB\n");
1235
    b.commit("b-edit", &[]).unwrap();
1236
    let pr = b.pull("origin").unwrap();
1237
    assert!(pr.changed && pr.checked_out);
1238
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
1239
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
1240
    write(&root.join("b"), "f.txt", b"a\nAB\n");
1241
    let hr = b.commit("resolve", &[]).unwrap();
1242
    assert_eq!(
1243
        b.store().get_change(&hr).unwrap().kind,
1244
        ChangeKind::Resolution
1245
    );
1246
    assert!(b.push("origin", false).unwrap()[0].ok);
1247
    origin.refresh().unwrap();
1248
    a.pull("origin").unwrap();
1249
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
1250
    // The resolution depends on the conflicting edits, but nothing depends
1251
    // on "third" (it only added g.txt), so it stays a head beside it.
1252
    let mut want = vec![hr, h3];
1253
    want.sort();
1254
    assert_eq!(a.bookmark_heads().unwrap(), want);
1255
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
1256
}
1257
1258
#[test]
1259
fn receive_push_rejects_bad_updates() {
1260
    hermetic();
1261
    let dir = tempfile::tempdir().unwrap();
1262
    let root = dir.path();
1263
    let origin = Repo::init(&root.join("origin")).unwrap();
1264
    let url = root.join("origin").to_string_lossy().to_string();
1265
    let mut a = Repo::clone(&url, &root.join("a"))
1266
        .unwrap()
1267
        .with_home(root.join("home"));
1268
    let (key, _) = a
1269
        .create_identity("Ada", "a@b", IdentityScope::Repo)
1270
        .unwrap();
1271
    write(&root.join("a"), "f.txt", b"x\n");
1272
    let h1 = a.commit("one", &[]).unwrap();
1273
    assert!(a.push("origin", false).unwrap()[0].ok);
1274
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
1275
    let s1 = origin
1276
        .store()
1277
        .put_state(&StateObject::new(vec![h1]))
1278
        .unwrap();
1279
1280
    // Missing head.
1281
    let ghost = origin
1282
        .store()
1283
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
1284
        .unwrap();
1285
    let r = origin
1286
        .receive_push(
1287
            Bundle::default(),
1288
            vec![RefUpdate {
1289
                name: "main".into(),
1290
                old_state: s1,
1291
                new_state: ghost,
1292
                force: false,
1293
                attestation: None,
1294
            }],
1295
            None,
1296
            vec![],
1297
        )
1298
        .unwrap();
1299
    assert!(
1300
        !r[0].ok && r[0].reason.contains("missing"),
1301
        "{}",
1302
        r[0].reason
1303
    );
1304
1305
    // Stale old_state.
1306
    let r = origin
1307
        .receive_push(
1308
            Bundle::default(),
1309
            vec![RefUpdate {
1310
                name: "main".into(),
1311
                old_state: empty,
1312
                new_state: s1,
1313
                force: false,
1314
                attestation: None,
1315
            }],
1316
            None,
1317
            vec![],
1318
        )
1319
        .unwrap();
1320
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
1321
1322
    // Non-fast-forward without force is refused; with force it passes.
1323
    let r = origin
1324
        .receive_push(
1325
            Bundle::default(),
1326
            vec![RefUpdate {
1327
                name: "main".into(),
1328
                old_state: s1,
1329
                new_state: empty,
1330
                force: false,
1331
                attestation: None,
1332
            }],
1333
            None,
1334
            vec![],
1335
        )
1336
        .unwrap();
1337
    assert!(
1338
        !r[0].ok && r[0].reason.contains("fast-forward"),
1339
        "{}",
1340
        r[0].reason
1341
    );
1342
    let r = origin
1343
        .receive_push(
1344
            Bundle::default(),
1345
            vec![RefUpdate {
1346
                name: "main".into(),
1347
                old_state: s1,
1348
                new_state: empty,
1349
                force: true,
1350
                attestation: None,
1351
            }],
1352
            None,
1353
            vec![],
1354
        )
1355
        .unwrap();
1356
    assert!(r[0].ok);
1357
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
1358
1359
    // Attestation with a stale serial is a rollback and is refused.
1360
    let sa = a
1361
        .sign_attest(&Attest {
1362
            repo: a.id().unwrap(),
1363
            hlc: Hlc::now(),
1364
            body: AttestBody::Ref {
1365
                name: "main".into(),
1366
                old_state: empty,
1367
                new_state: s1,
1368
                serial: 1,
1369
            },
1370
        })
1371
        .unwrap();
1372
    let r = origin
1373
        .receive_push(
1374
            Bundle::default(),
1375
            vec![RefUpdate {
1376
                name: "main".into(),
1377
                old_state: empty,
1378
                new_state: s1,
1379
                force: false,
1380
                attestation: Some(sa.clone()),
1381
            }],
1382
            None,
1383
            vec![],
1384
        )
1385
        .unwrap();
1386
    assert!(
1387
        !r[0].ok && r[0].reason.contains("serial"),
1388
        "{}",
1389
        r[0].reason
1390
    );
1391
    // An attestation for a different update is refused too.
1392
    let sa2 = a
1393
        .sign_attest(&Attest {
1394
            repo: a.id().unwrap(),
1395
            hlc: Hlc::now(),
1396
            body: AttestBody::Ref {
1397
                name: "main".into(),
1398
                old_state: s1,
1399
                new_state: empty,
1400
                serial: 5,
1401
            },
1402
        })
1403
        .unwrap();
1404
    let r = origin
1405
        .receive_push(
1406
            Bundle::default(),
1407
            vec![RefUpdate {
1408
                name: "main".into(),
1409
                old_state: empty,
1410
                new_state: s1,
1411
                force: false,
1412
                attestation: Some(sa2),
1413
            }],
1414
            None,
1415
            vec![],
1416
        )
1417
        .unwrap();
1418
    assert!(
1419
        !r[0].ok && r[0].reason.contains("describe"),
1420
        "{}",
1421
        r[0].reason
1422
    );
1423
    let _ = key;
1424
}
1425
1426
#[test]
1427
fn user_config_supplies_defaults_and_clones_sign() {
1428
    hermetic();
1429
    let dir = tempfile::tempdir().unwrap();
1430
    let root = dir.path();
1431
    let home = root.join("home");
1432
    let origin = Repo::init(&root.join("origin")).unwrap();
1433
    let url = root.join("origin").to_string_lossy().to_string();
1434
1435
    // Identity at user scope: the repository file stays free of author keys.
1436
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
1437
    let (key, _) = a
1438
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1439
        .unwrap();
1440
    assert!(!a.config.repo_layer().contains_key("author.key"));
1441
    assert_eq!(a.config.author_key, Some(key));
1442
    assert!(home.join("config.toml").exists());
1443
    a.set_user_config("core.sign", "change").unwrap();
1444
    assert!(a.config.sign_changes);
1445
1446
    // Repository settings override user settings and are the only ones saved.
1447
    a.config.set("core.sign", "seal").unwrap();
1448
    a.save_config().unwrap();
1449
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
1450
    assert!(!again.config.sign_changes);
1451
    assert_eq!(again.config.author_key, Some(key));
1452
    assert_eq!(
1453
        read_config_file(&root.join("a/.oxy/config"))
1454
            .unwrap()
1455
            .get("core.sign")
1456
            .map(String::as_str),
1457
        Some("seal")
1458
    );
1459
1460
    // A fresh clone made by this user signs with the user-level identity,
1461
    // even though the clone's store has never seen the identity object.
1462
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
1463
    assert!(b.config.sign_changes);
1464
    write(&root.join("b"), "f.txt", b"f\n");
1465
    let h = b.commit("signed from a clone", &[]).unwrap();
1466
    assert!(
1467
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
1468
    );
1469
    assert!(b.push("origin", false).unwrap()[0].ok);
1470
    assert!(matches!(
1471
        origin.verify_change(&h).unwrap(),
1472
        SignatureStatus::Valid { .. }
1473
    ));
1474
}
1475
1476
#[test]
1477
fn format1_repositories_are_migrated_on_open() {
1478
    hermetic();
1479
    use crate::oplog::{Format1Op, Format1View};
1480
    let dir = tempfile::tempdir().unwrap();
1481
    let root = dir.path();
1482
    let repo = Repo::init(root).unwrap();
1483
    write(root, "a.txt", b"a\n");
1484
    let h1 = repo.commit("one", &[]).unwrap();
1485
    let (wc_hash, _) = repo.working_copy().unwrap();
1486
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
1487
    let mut v1 = Format1View::default();
1488
    v1.bookmarks.insert("main".into(), vec![]);
1489
    v1.workspaces.insert(repo.workspace(), wc_hash);
1490
    let init = Format1Op {
1491
        parents: vec![],
1492
        hlc: Hlc::default(),
1493
        command: "oxy init".into(),
1494
        view: v1.clone(),
1495
    };
1496
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
1497
    v1.bookmarks.insert("main".into(), vec![h1]);
1498
    let commit = Format1Op {
1499
        parents: vec![init_ref],
1500
        hlc: Hlc::default(),
1501
        command: "oxy commit".into(),
1502
        view: v1,
1503
    };
1504
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
1505
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
1506
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
1507
    drop(repo);
1508
1509
    let repo = Repo::open(root).unwrap();
1510
    assert_eq!(
1511
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
1512
        FORMAT_LINE
1513
    );
1514
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
1515
    let ops = repo.op_log().unwrap();
1516
    assert_eq!(
1517
        ops.iter()
1518
            .map(|(_, o)| o.command.as_str())
1519
            .collect::<Vec<_>>(),
1520
        ["oxy commit", "oxy init"]
1521
    );
1522
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
1523
    assert!(!repo.snapshot("status").unwrap().changed);
1524
    // Reopening again is a no-op.
1525
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
1526
}
1527
1528
#[test]
1529
fn undo_skips_snapshot_operations() {
1530
    hermetic();
1531
    let dir = tempfile::tempdir().unwrap();
1532
    let root = dir.path();
1533
    let repo = Repo::init(root).unwrap();
1534
    write(root, "a.txt", b"a\n");
1535
    let h1 = repo.commit("a", &[]).unwrap();
1536
    // A later command snapshots new edits on top of the commit.
1537
    write(root, "b.txt", b"b\n");
1538
    let s = repo.snapshot("oxy status").unwrap();
1539
    assert!(s.changed);
1540
    assert!(repo.head_op().unwrap().1.is_snapshot());
1541
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
1542
    // Undo must undo the commit, not the snapshot.
1543
    repo.undo().unwrap();
1544
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
1545
    let s = repo.snapshot("oxy status").unwrap();
1546
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
1547
    assert_eq!(
1548
        paths,
1549
        ["a.txt", "b.txt"],
1550
        "both files are back in the working copy"
1551
    );
1552
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
1553
    // Only snapshots remain above `init`, so there is nothing left to undo.
1554
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
1555
    assert!(repo.undo().is_err());
1556
}
1557
1558
#[test]
1559
fn independent_changes_commute_and_make_multiple_heads() {
1560
    hermetic();
1561
    let dir = tempfile::tempdir().unwrap();
1562
    let root = dir.path();
1563
    let repo = Repo::init(root).unwrap();
1564
    write(root, "a.txt", b"a\n");
1565
    let h1 = repo.commit("a", &[]).unwrap();
1566
    write(root, "b.txt", b"b\n");
1567
    let h2 = repo.commit("b", &[]).unwrap();
1568
    let c2 = repo.store().get_change(&h2).unwrap();
1569
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
1570
    let mut heads = repo.bookmark_heads().unwrap();
1571
    heads.sort();
1572
    let mut want = vec![h1, h2];
1573
    want.sort();
1574
    assert_eq!(heads, want);
1575
    // Editing a.txt depends on h1 only.
1576
    write(root, "a.txt", b"a\na2\n");
1577
    let h3 = repo.commit("a2", &[]).unwrap();
1578
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
1579
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1580
    assert_eq!(heads, [h2, h3].into_iter().collect());
1581
    // Explicit dependency.
1582
    write(root, "c.txt", b"c\n");
1583
    let h4 = repo.commit("c", &[h2]).unwrap();
1584
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
1585
}
1586
1587
#[test]
1588
fn mode_change_and_text_binary_switch() {
1589
    hermetic();
1590
    let dir = tempfile::tempdir().unwrap();
1591
    let root = dir.path();
1592
    let repo = Repo::init(root).unwrap();
1593
    write(root, "run.sh", b"#!/bin/sh\n");
1594
    repo.commit("add script", &[]).unwrap();
1595
    #[cfg(unix)]
1596
    {
1597
        use std::os::unix::fs::PermissionsExt;
1598
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1599
        let s = repo.snapshot("status").unwrap();
1600
        assert_eq!(
1601
            statuses(&s),
1602
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
1603
        );
1604
        let h = repo.commit("exec", &[]).unwrap();
1605
        let snap = repo.load_state(&[h]).unwrap().materialize();
1606
        assert!(snap.files["run.sh"].mode.exec);
1607
    }
1608
    // Text → binary → text.
1609
    write(root, "run.sh", b"\0binary");
1610
    let h = repo.commit("binary", &[]).unwrap();
1611
    let snap = repo.load_state(&[h]).unwrap().materialize();
1612
    assert!(snap.files["run.sh"].mode.opaque);
1613
    write(root, "run.sh", b"text again\n");
1614
    let h = repo.commit("text", &[]).unwrap();
1615
    let snap = repo.load_state(&[h]).unwrap().materialize();
1616
    assert!(!snap.files["run.sh"].mode.opaque);
1617
    assert!(
1618
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
1619
    );
1620
    assert!(!snap.is_conflicted());
1621
}
1622
1623
/// oxygen#87: a binary file given new contents and the executable bit in
1624
/// one commit kept the contents and lost the bit.
1625
#[cfg(unix)]
1626
#[test]
1627
fn a_binary_file_changed_and_made_executable_at_once_keeps_both() {
1628
    use std::os::unix::fs::PermissionsExt;
1629
    hermetic();
1630
    let dir = tempfile::tempdir().unwrap();
1631
    let root = dir.path();
1632
    let repo = Repo::init(root).unwrap();
1633
    write(root, "tool.exe", b"MZ\0one");
1634
    repo.commit("add", &[]).unwrap();
1635
    write(root, "tool.exe", b"MZ\0two");
1636
    fs::set_permissions(root.join("tool.exe"), fs::Permissions::from_mode(0o755)).unwrap();
1637
    let h = repo.commit("update and +x", &[]).unwrap();
1638
    let snap = repo.load_state(&[h]).unwrap().materialize();
1639
    let f = &snap.files["tool.exe"];
1640
    assert!(f.mode.opaque && f.mode.exec, "{:?}", f.mode);
1641
    assert!(
1642
        repo.snapshot("status").unwrap().statuses.is_empty(),
1643
        "nothing left to commit"
1644
    );
1645
}
1646
1647
/// Keyless step 4 (oxygenhub#241): an agent signing with a short-lived
1648
/// key whose certificate an issuer gave pushes when the policy grants its
1649
/// subject, and a fetch accepts what it attested; an expired certificate,
1650
/// or a subject the policy does not grant, may not move the bookmark.
1651
#[test]
1652
fn a_certified_key_pushes_under_a_subject_grant() {
1653
    use crate::cert::{Certificate, SignedCertificate};
1654
    use crate::identity::Scope;
1655
    hermetic();
1656
    let dir = tempfile::tempdir().unwrap();
1657
    let root = dir.path();
1658
    let _origin = Repo::init(&root.join("origin")).unwrap();
1659
    let url = root.join("origin").to_string_lossy().to_string();
1660
    let mut a = Repo::clone(&url, &root.join("a"))
1661
        .unwrap()
1662
        .with_home(root.join("home-a"));
1663
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1664
        .unwrap();
1665
    write(&root.join("a"), "a.txt", b"a\n");
1666
    a.commit("a", &[]).unwrap();
1667
    a.policy_init().unwrap();
1668
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1669
    let hub_sk = SecretKey::generate();
1670
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1671
    a.policy_grant_subject(
1672
        "agent:claude@ada",
1673
        hub.clone(),
1674
        Scope::CHANGES | Scope::REFS,
1675
        None,
1676
    )
1677
    .unwrap();
1678
    assert!(a
1679
        .push("origin", false)
1680
        .unwrap()
1681
        .iter()
1682
        .any(|r| r.name == "policy" && r.ok));
1683
1684
    let now = Hlc::now().wall_ms;
1685
    // An agent repository whose key the hub certified for `subject`, from
1686
    // `from` to `to`.
1687
    let agent = |name: &str, subject: &str, from: u64, to: u64| {
1688
        let mut r = Repo::clone(&url, &root.join(name))
1689
            .unwrap()
1690
            .with_home(root.join(format!("home-{name}")));
1691
        let (_, id) = r
1692
            .create_identity(name, "[email protected]", IdentityScope::User)
1693
            .unwrap();
1694
        let cert = SignedCertificate::sign(
1695
            Certificate {
1696
                key: id,
1697
                issuer: hub.hash(),
1698
                subject: subject.into(),
1699
                claims: vec![],
1700
                scope: Scope::CHANGES | Scope::REFS,
1701
                not_before: from,
1702
                expires: to,
1703
                grant: None,
1704
            },
1705
            &hub,
1706
            &hub_sk,
1707
        );
1708
        r.store().put_identity(&hub).unwrap();
1709
        r.store().put_certificate(&cert).unwrap();
1710
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1711
        r.commit("work", &[]).unwrap();
1712
        r
1713
    };
1714
1715
    let claude = agent("claude", "agent:claude@ada", now - 60_000, now + 600_000);
1716
    let r = claude.push("origin", false).unwrap();
1717
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1718
    // Ada's fetch accepts the bookmark the certified key attested.
1719
    a.pull("origin").unwrap();
1720
    assert!(a.bookmark_heads().unwrap().iter().any(|h| a
1721
        .store()
1722
        .get_change(h)
1723
        .map(|c| c.message == "work")
1724
        .unwrap_or(false)));
1725
1726
    // Step 4c: a host with an acceptor key records when it accepted the
1727
    // certified update and serves it; a fetch checks the certificate at
1728
    // that time only when the certificate's issuer signed it for exactly
1729
    // this attestation, else at the attestation's own time.
1730
    let host = Repo::open(&root.join("origin"))
1731
        .unwrap()
1732
        .with_acceptor(hub.clone(), hub_sk.clone());
1733
    let (attest_ref, sa) = host.latest_ref_attest("main").unwrap().unwrap();
1734
    host.record_acceptance(&attest_ref).unwrap();
1735
    let served = host.remote_refs().unwrap();
1736
    let acc = served
1737
        .refs
1738
        .iter()
1739
        .find(|r| r.name == "main")
1740
        .unwrap()
1741
        .accepted
1742
        .clone()
1743
        .expect("served with the refs");
1744
    let signer = sa.sigs[0].key;
1745
    assert_eq!(
1746
        a.certified_time(&signer, &sa, Some(&acc)),
1747
        acc.attest.hlc.wall_ms
1748
    );
1749
    assert_eq!(a.certified_time(&signer, &sa, None), sa.attest.hlc.wall_ms);
1750
    let stranger_sk = SecretKey::generate();
1751
    let stranger = stranger_sk.identity("stranger", "s@x", 1);
1752
    let mut forged = acc.clone();
1753
    forged.sigs = vec![stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.attest.hash())];
1754
    assert_eq!(
1755
        a.certified_time(&signer, &sa, Some(&forged)),
1756
        sa.attest.hlc.wall_ms,
1757
        "not the issuer's"
1758
    );
1759
    let mut elsewhere = acc.clone();
1760
    elsewhere.attest.body = AttestBody::Accepted {
1761
        attest: ObjectRef([7; 32]),
1762
    };
1763
    elsewhere.sigs = vec![hub_sk.sign(Domain::Attest, &hub.hash(), &elsewhere.attest.hash())];
1764
    assert_eq!(
1765
        a.certified_time(&signer, &sa, Some(&elsewhere)),
1766
        sa.attest.hlc.wall_ms,
1767
        "another attestation's"
1768
    );
1769
    a.pull("origin").unwrap();
1770
    // gc keeps the acceptance with the attestation.
1771
    host.gc(true).unwrap();
1772
    assert!(host.acceptance_of(&attest_ref).unwrap().is_some());
1773
1774
    let late = agent("late", "agent:claude@ada", now - 1_200_000, now - 600_000);
1775
    let r = late.push("origin", false).unwrap();
1776
    assert!(
1777
        !r[0].ok && r[0].reason.contains("may not update"),
1778
        "an expired certificate: {r:?}"
1779
    );
1780
    let other = agent("other", "agent:mallory@ada", now - 60_000, now + 600_000);
1781
    let r = other.push("origin", false).unwrap();
1782
    assert!(
1783
        !r[0].ok && r[0].reason.contains("may not update"),
1784
        "a subject not granted: {r:?}"
1785
    );
1786
}
1787
1788
/// A tag made under one short-lived key and pushed under another: its
1789
/// signer travels with the push (identity and certificate), so a receiver
1790
/// that has never seen that key accepts it. A tag-only push by a keyless
1791
/// agent was refused "unknown key" (found releasing OxygenFlow 0.2.0).
1792
#[test]
1793
fn a_tag_signed_by_an_earlier_short_lived_key_is_pushed() {
1794
    use crate::cert::{Certificate, SignedCertificate};
1795
    use crate::identity::Scope;
1796
    hermetic();
1797
    let dir = tempfile::tempdir().unwrap();
1798
    let root = dir.path();
1799
    let _origin = Repo::init(&root.join("origin")).unwrap();
1800
    let url = root.join("origin").to_string_lossy().to_string();
1801
    let mut a = Repo::clone(&url, &root.join("a"))
1802
        .unwrap()
1803
        .with_home(root.join("home-a"));
1804
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1805
        .unwrap();
1806
    write(&root.join("a"), "a.txt", b"a\n");
1807
    a.commit("a", &[]).unwrap();
1808
    a.policy_init().unwrap();
1809
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1810
    let hub_sk = SecretKey::generate();
1811
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1812
    a.policy_grant_subject(
1813
        "agent:claude@ada",
1814
        hub.clone(),
1815
        Scope::CHANGES | Scope::REFS,
1816
        Some("*"),
1817
    )
1818
    .unwrap();
1819
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1820
1821
    let now = Hlc::now().wall_ms;
1822
    let mut agent = Repo::clone(&url, &root.join("agent"))
1823
        .unwrap()
1824
        .with_home(root.join("home-agent"));
1825
    agent.store().put_identity(&hub).unwrap();
1826
    let certify = |agent: &Repo, id| {
1827
        let cert = SignedCertificate::sign(
1828
            Certificate {
1829
                key: id,
1830
                issuer: hub.hash(),
1831
                subject: "agent:claude@ada".into(),
1832
                claims: vec![],
1833
                scope: Scope::CHANGES | Scope::REFS,
1834
                not_before: now - 60_000,
1835
                expires: now + 600_000,
1836
                grant: None,
1837
            },
1838
            &hub,
1839
            &hub_sk,
1840
        );
1841
        agent.store().put_certificate(&cert).unwrap();
1842
    };
1843
    // The tag, under the first short-lived key.
1844
    let (first, first_id) = agent
1845
        .create_identity("claude", "[email protected]", IdentityScope::User)
1846
        .unwrap();
1847
    certify(&agent, first_id);
1848
    let heads = agent.bookmark_heads().unwrap();
1849
    agent.tag_create("v1", &heads, "first").unwrap();
1850
    // The push, under a second one (a later process's ten-minute key).
1851
    let (second, second_id) = agent
1852
        .create_identity("claude", "[email protected]", IdentityScope::User)
1853
        .unwrap();
1854
    assert_ne!(first, second);
1855
    certify(&agent, second_id);
1856
    agent
1857
        .set_user_config("author.signer", &second.to_hex())
1858
        .unwrap();
1859
    let host = Repo::open(&root.join("origin")).unwrap();
1860
    assert!(
1861
        host.store().get_identity(&first).is_err(),
1862
        "the host has never seen the tag's key"
1863
    );
1864
    let r = agent.push("origin", false).unwrap();
1865
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1866
    let host = Repo::open(&root.join("origin")).unwrap();
1867
    assert!(
1868
        host.tag_refs().unwrap().iter().any(|t| t.name == "v1"),
1869
        "the tag arrived"
1870
    );
1871
}
1872
1873
/// oxygen#129: a short-lived key's tag is checked on a fetch at a time its
1874
/// signer did not choose, its issuer's acceptance, never at the time it
1875
/// claims nor at the fetch's (when the ten-minute certificate has long
1876
/// expired). Without an acceptance it is left out and said so; with one
1877
/// inside the certificate's window it is fetched however much later, and
1878
/// a host it is pushed on to keeps and serves the acceptance.
1879
#[test]
1880
fn a_short_lived_key_s_tag_is_fetched_at_its_issuer_s_acceptance() {
1881
    use crate::cert::{Certificate, SignedCertificate};
1882
    use crate::identity::Scope;
1883
    hermetic();
1884
    let dir = tempfile::tempdir().unwrap();
1885
    let root = dir.path();
1886
    let _origin = Repo::init(&root.join("origin")).unwrap();
1887
    let url = root.join("origin").to_string_lossy().to_string();
1888
    let mut a = Repo::clone(&url, &root.join("a"))
1889
        .unwrap()
1890
        .with_home(root.join("home-a"));
1891
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1892
        .unwrap();
1893
    write(&root.join("a"), "a.txt", b"a\n");
1894
    a.commit("a", &[]).unwrap();
1895
    a.policy_init().unwrap();
1896
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1897
    let hub_sk = SecretKey::generate();
1898
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1899
    a.policy_grant_subject(
1900
        "agent:claude@ada",
1901
        hub.clone(),
1902
        Scope::CHANGES | Scope::REFS,
1903
        Some("*"),
1904
    )
1905
    .unwrap();
1906
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1907
1908
    let now = Hlc::now().wall_ms;
1909
    // An agent whose key the hub certified from `from` to `to`.
1910
    let agent = |name: &str, from: u64, to: u64| {
1911
        let mut r = Repo::clone(&url, &root.join(name))
1912
            .unwrap()
1913
            .with_home(root.join(format!("home-{name}")));
1914
        r.store().put_identity(&hub).unwrap();
1915
        let (_, id) = r
1916
            .create_identity(name, "[email protected]", IdentityScope::User)
1917
            .unwrap();
1918
        let cert = SignedCertificate::sign(
1919
            Certificate {
1920
                key: id,
1921
                issuer: hub.hash(),
1922
                subject: "agent:claude@ada".into(),
1923
                claims: vec![],
1924
                scope: Scope::CHANGES | Scope::REFS,
1925
                not_before: from,
1926
                expires: to,
1927
                grant: None,
1928
            },
1929
            &hub,
1930
            &hub_sk,
1931
        );
1932
        r.store().put_certificate(&cert).unwrap();
1933
        r
1934
    };
1935
1936
    // A tag by a key certified now, pushed to a host that records no
1937
    // acceptance (a path on disk): it lands, but a fetch has no time to
1938
    // check its certificate at, so it is left out and the fetch goes on.
1939
    let claude = agent("claude", now - 60_000, now + 600_000);
1940
    let heads = claude.bookmark_heads().unwrap();
1941
    claude.tag_create("v1", &heads, "one").unwrap();
1942
    let r = claude.push("origin", false).unwrap();
1943
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1944
    let b = Repo::clone(&url, &root.join("b"))
1945
        .unwrap()
1946
        .with_home(root.join("home-b"));
1947
    let rep = b.fetch("origin").unwrap();
1948
    assert!(
1949
        rep.skipped
1950
            .iter()
1951
            .any(|(n, why)| n == "tags/v1" && why.contains("no time to check its certificate at")),
1952
        "{rep:?}"
1953
    );
1954
    assert_eq!(b.tag_heads("v1").unwrap(), None);
1955
1956
    // The host's acceptance, signed by the certificate's issuer, served
1957
    // with the tag: fetched.
1958
    let host = Repo::open(&root.join("origin"))
1959
        .unwrap()
1960
        .with_acceptor(hub.clone(), hub_sk.clone());
1961
    let (v1, _) = host.tag_attest("v1").unwrap().unwrap();
1962
    host.record_acceptance(&v1).unwrap();
1963
    let served = host.tag_refs().unwrap();
1964
    assert!(served
1965
        .iter()
1966
        .any(|t| t.name == "v1" && t.accepted.is_some()));
1967
    let rep = b.fetch("origin").unwrap();
1968
    assert!(rep.skipped.is_empty(), "{rep:?}");
1969
    assert_eq!(b.tag_heads("v1").unwrap(), Some(heads.clone()));
1970
    // gc keeps the acceptance with the tag.
1971
    host.gc(true).unwrap();
1972
    assert!(host.acceptance_of(&v1).unwrap().is_some());
1973
1974
    // Long after: a key whose certificate expired an hour ago may not
1975
    // create a tag now.
1976
    let late = agent("late", now - 7_200_000, now - 3_600_000);
1977
    late.tag_create("v2", &heads, "two").unwrap();
1978
    let r = late.push("origin", false).unwrap();
1979
    assert!(
1980
        r.iter()
1981
            .any(|x| x.name == "tags/v2" && !x.ok && x.reason.contains("may not create")),
1982
        "{r:?}"
1983
    );
1984
    // With its issuer's acceptance from inside the window (as a hub gave
1985
    // it then, passed on to another host), it is taken at that time: by
1986
    // the host it is pushed to, which keeps it, and by a fresh clone.
1987
    let (v2, _) = late.tag_attest("v2").unwrap().unwrap();
1988
    let acc = Attest {
1989
        repo: late.id().unwrap(),
1990
        hlc: Hlc {
1991
            wall_ms: now - 5_400_000,
1992
            logical: 0,
1993
        },
1994
        body: AttestBody::Accepted { attest: v2 },
1995
    };
1996
    let sig = hub_sk.sign(Domain::Attest, &hub.hash(), &acc.hash());
1997
    // One by any other key gives no time.
1998
    let stranger_sk = SecretKey::generate();
1999
    let stranger = stranger_sk.identity("stranger", "[email protected]", 1);
2000
    let forged = stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.hash());
2001
    late.keep_acceptance(
2002
        &v2,
2003
        &SignedAttest {
2004
            attest: acc.clone(),
2005
            sigs: vec![forged],
2006
        },
2007
    )
2008
    .unwrap();
2009
    let r = late.push("origin", false).unwrap();
2010
    assert!(
2011
        r.iter().any(|x| x.name == "tags/v2" && !x.ok),
2012
        "not the issuer's: {r:?}"
2013
    );
2014
    let theirs = SignedAttest {
2015
        attest: acc,
2016
        sigs: vec![sig],
2017
    };
2018
    // Kept beside the stranger's: the issuer's is the one sent.
2019
    late.keep_acceptance(&v2, &theirs).unwrap();
2020
    let r = late.push("origin", false).unwrap();
2021
    // (Its re-attestation of main is refused: an expired key moves no
2022
    // bookmark.)
2023
    assert!(r.iter().any(|x| x.name == "tags/v2" && x.ok), "{r:?}");
2024
    let host = Repo::open(&root.join("origin")).unwrap();
2025
    let (hv2, _) = host.tag_attest("v2").unwrap().unwrap();
2026
    assert_eq!(hv2, v2);
2027
    assert!(host
2028
        .store()
2029
        .index_get_pub("accepted", &v2)
2030
        .unwrap()
2031
        .contains(&theirs.attest.hash()));
2032
    let c = Repo::clone(&url, &root.join("c"))
2033
        .unwrap()
2034
        .with_home(root.join("home-c"));
2035
    assert_eq!(c.tag_heads("v2").unwrap(), Some(heads.clone()));
2036
    assert_eq!(c.tag_heads("v1").unwrap(), Some(heads));
2037
}
2038
2039
/// oxygenhub#266: a short-lived key its issuer certified moves a bookmark
2040
/// and signs no change (a keyless agent naming a bookmark). A third
2041
/// party's clone gets the key's identity, its certificate and the
2042
/// issuer's identity with the fetch, so the policy's subject grant
2043
/// authorizes the move and the signature verifies.
2044
#[test]
2045
fn a_bookmark_moved_by_a_certified_key_alone_is_fetched() {
2046
    use crate::cert::{Certificate, SignedCertificate};
2047
    use crate::identity::Scope;
2048
    hermetic();
2049
    let dir = tempfile::tempdir().unwrap();
2050
    let root = dir.path();
2051
    let _origin = Repo::init(&root.join("origin")).unwrap();
2052
    let url = root.join("origin").to_string_lossy().to_string();
2053
    let mut a = Repo::clone(&url, &root.join("a"))
2054
        .unwrap()
2055
        .with_home(root.join("home-a"));
2056
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
2057
        .unwrap();
2058
    write(&root.join("a"), "a.txt", b"a\n");
2059
    a.commit("a", &[]).unwrap();
2060
    a.policy_init().unwrap();
2061
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2062
    let hub_sk = SecretKey::generate();
2063
    let hub = hub_sk.identity("hub", "[email protected]", 1);
2064
    a.policy_grant_subject(
2065
        "agent:claude@ada",
2066
        hub.clone(),
2067
        Scope::CHANGES | Scope::REFS,
2068
        None,
2069
    )
2070
    .unwrap();
2071
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2072
2073
    let now = Hlc::now().wall_ms;
2074
    let mut agent = Repo::clone(&url, &root.join("agent"))
2075
        .unwrap()
2076
        .with_home(root.join("home-agent"));
2077
    let (key, id) = agent
2078
        .create_identity("claude", "[email protected]", IdentityScope::User)
2079
        .unwrap();
2080
    let cert = SignedCertificate::sign(
2081
        Certificate {
2082
            key: id,
2083
            issuer: hub.hash(),
2084
            subject: "agent:claude@ada".into(),
2085
            claims: vec![],
2086
            scope: Scope::CHANGES | Scope::REFS,
2087
            not_before: now - 60_000,
2088
            expires: now + 600_000,
2089
            grant: None,
2090
        },
2091
        &hub,
2092
        &hub_sk,
2093
    );
2094
    agent.store().put_identity(&hub).unwrap();
2095
    agent.store().put_certificate(&cert).unwrap();
2096
    let heads = agent.bookmark_heads().unwrap();
2097
    agent.bookmark_create("agent-work", Some(&heads)).unwrap();
2098
    let r = agent.push_bookmark("origin", "agent-work", false).unwrap();
2099
    assert!(r.iter().all(|x| x.ok), "{r:?}");
2100
    let host = Repo::open(&root.join("origin")).unwrap();
2101
    let (_, sa) = host.latest_ref_attest("agent-work").unwrap().unwrap();
2102
    assert_eq!(sa.sigs[0].key, key, "the certified key alone moved it");
2103
2104
    // A fetch naming no change brings the certificate and both identities.
2105
    let bundle = host.bundle_raw_for(&[], None).unwrap();
2106
    assert!(bundle.changes.is_empty() && bundle.raw_changes.is_empty());
2107
    assert_eq!(bundle.certificates.len(), 1);
2108
    for k in [key, hub.hash()] {
2109
        assert!(bundle
2110
            .objects
2111
            .iter()
2112
            .any(|(t, b)| *t == ObjectType::Identity && hash_object(*t, b) == k));
2113
    }
2114
2115
    let c = Repo::clone(&url, &root.join("c")).unwrap();
2116
    let tracked = c.view().unwrap().remotes["origin"].clone();
2117
    assert_eq!(
2118
        tracked.get("agent-work"),
2119
        host.view().unwrap().bookmarks.get("agent-work")
2120
    );
2121
    assert!(c.store().certificate_of(&key).unwrap().is_some());
2122
}
2123
2124
/// Trusted time (oxygenhub#240, spec §14.8): a fetched attestation by a
2125
/// short-lived key is judged at its integrated time, the earliest time a
2126
/// pinned witness cosigned a checkpoint holding it. A certificate valid
2127
/// then but expired now passes; a witness this user does not trust gives
2128
/// no time (the earlier rule, said so); a backdated attestation is noted;
2129
/// an answer without the new fields is judged as before.
2130
#[test]
2131
fn a_fetched_attestation_is_judged_at_its_integrated_time() {
2132
    use super::transparency::LogCheck;
2133
    use crate::cert::{Certificate, SignedCertificate};
2134
    use crate::identity::Scope;
2135
    use crate::protocol::{Integration, Logged, RefsResponse, RemoteRef};
2136
    use crate::tlog::{self, Checkpoint, Entry, Hash, Integrated, Note};
2137
    hermetic();
2138
    let dir = tempfile::tempdir().unwrap();
2139
    let root = dir.path();
2140
    let mut a = Repo::init(&root.join("a"))
2141
        .unwrap()
2142
        .with_home(root.join("home-a"));
2143
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
2144
        .unwrap();
2145
    write(&root.join("a"), "a.txt", b"a\n");
2146
    a.commit("a", &[]).unwrap();
2147
    a.policy_init().unwrap();
2148
    let issuer_sk = SecretKey::generate();
2149
    let issuer = issuer_sk.identity("hub", "[email protected]", 1);
2150
    a.policy_grant_subject(
2151
        "agent:claude@ada",
2152
        issuer.clone(),
2153
        Scope::CHANGES | Scope::REFS,
2154
        None,
2155
    )
2156
    .unwrap();
2157
    let p = a.current_policy().unwrap().unwrap().1.policy;
2158
2159
    // An agent key the issuer certified for ten minutes two hours ago.
2160
    let now = Hlc::now().wall_ms;
2161
    let t0 = now - 2 * 3_600_000;
2162
    let agent_sk = SecretKey::generate();
2163
    let agent = agent_sk.identity("claude", "[email protected]", t0);
2164
    let cert = SignedCertificate::sign(
2165
        Certificate {
2166
            key: agent.clone(),
2167
            issuer: issuer.hash(),
2168
            subject: "agent:claude@ada".into(),
2169
            claims: vec![],
2170
            scope: Scope::CHANGES | Scope::REFS,
2171
            not_before: t0,
2172
            expires: t0 + 600_000,
2173
            grant: None,
2174
        },
2175
        &issuer,
2176
        &issuer_sk,
2177
    );
2178
    a.store().put_identity(&agent).unwrap();
2179
    a.store().put_certificate(&cert).unwrap();
2180
    let signer = agent.hash();
2181
    let attested = |claimed: u64| {
2182
        let attest = Attest {
2183
            repo: a.id().unwrap(),
2184
            hlc: Hlc {
2185
                wall_ms: claimed,
2186
                logical: 0,
2187
            },
2188
            body: AttestBody::Ref {
2189
                name: "main".into(),
2190
                old_state: ObjectRef([1; 32]),
2191
                new_state: ObjectRef([2; 32]),
2192
                serial: 1,
2193
            },
2194
        };
2195
        let sig = agent_sk.sign(Domain::Attest, &signer, &attest.hash());
2196
        SignedAttest {
2197
            attest,
2198
            sigs: vec![sig],
2199
        }
2200
    };
2201
2202
    // The hub's log: eight entries, the attestation's at 3, the latest
2203
    // checkpoint of 8, and one of 4 that witnesses cosigned.
2204
    let log_sk = SecretKey::generate();
2205
    let log_key = log_sk.identity("hub.example", "[email protected]", 1);
2206
    let origin = "hub.example/log";
2207
    let hub = "https://hub.example";
2208
    let url = "https://hub.example/ada/a";
2209
    let w_sk = SecretKey::generate();
2210
    let w = w_sk.identity("w", "[email protected]", 1);
2211
    let stranger_sk = SecretKey::generate();
2212
    let stranger = stranger_sk.identity("s", "[email protected]", 1);
2213
    let sa = attested(t0 + 300_000);
2214
    let entry_of = |i: u64| {
2215
        let (kind, object) = if i == 3 {
2216
            ("ref", sa.attest.hash())
2217
        } else {
2218
            ("seal", ObjectRef([i as u8; 32]))
2219
        };
2220
        Entry {
2221
            kind: kind.into(),
2222
            repo: sa.attest.repo,
2223
            object,
2224
            signers: vec![signer],
2225
            received: t0 + 300_000,
2226
        }
2227
        .encode()
2228
    };
2229
    let mut stored: Vec<Hash> = Vec::new();
2230
    for i in 0..8 {
2231
        let add = tlog::stored_hashes_for_leaf(i, tlog::leaf_hash(&entry_of(i)), &stored).unwrap();
2232
        stored.extend(add);
2233
    }
2234
    let note_of = |n: u64, cosigners: &[(&str, &Identity, &SecretKey, u64)]| {
2235
        let mut note = Checkpoint {
2236
            origin: origin.into(),
2237
            size: n,
2238
            root: tlog::tree_hash(n, &stored).unwrap(),
2239
            extensions: vec![],
2240
        }
2241
        .sign(&log_key, &log_sk)
2242
        .unwrap();
2243
        for (name, id, sk, t) in cosigners {
2244
            note.sigs
2245
                .extend(tlog::cosign(&note.text, name, id, sk, *t).unwrap());
2246
        }
2247
        note.encode()
2248
    };
2249
    let latest = note_of(8, &[]);
2250
    let witnessed_at = (t0 + 360_000) / 1000;
2251
    let cosigned = note_of(
2252
        4,
2253
        &[
2254
            ("w.example", &w, &w_sk, witnessed_at),
2255
            ("s.example", &stranger, &stranger_sk, 1),
2256
        ],
2257
    );
2258
    let answer = |integration: Vec<Integration>, witnesses: Vec<(String, Vec<u8>)>| RefsResponse {
2259
        refs: vec![RemoteRef {
2260
            name: "main".into(),
2261
            state: ObjectRef([2; 32]),
2262
            heads: vec![],
2263
            attestation: Some(sa.clone()),
2264
            last_serial: None,
2265
            accepted: None,
2266
            logged: Some(Logged {
2267
                index: 3,
2268
                entry: entry_of(3),
2269
                proof: tlog::prove_inclusion(8, 3, &stored).unwrap(),
2270
            }),
2271
            integration,
2272
        }],
2273
        log: Some(latest.clone()),
2274
        witnesses,
2275
        ..RefsResponse::default()
2276
    };
2277
    let proof4 = tlog::prove_inclusion(4, 3, &stored).unwrap();
2278
    let served = vec![Integration {
2279
        note: cosigned.clone(),
2280
        proof: proof4.clone(),
2281
    }];
2282
    let listed = vec![("w.example".to_string(), w.encode())];
2283
    // This user saw the hub's log before (pinned, so nothing is fetched).
2284
    a.remember_log(hub, &log_key, &Note::parse(&latest).unwrap())
2285
        .unwrap();
2286
2287
    // The witness is pinned on first sight, silently; the stranger's
2288
    // earlier cosignature counts for nothing.
2289
    let resp = answer(served.clone(), listed.clone());
2290
    let lc = a.check_log(url, None, &resp).unwrap();
2291
    assert!(lc.notes.is_empty(), "{:?}", lc.notes);
2292
    let t = lc.time_of("main").unwrap();
2293
    assert_eq!((t.time, t.witness.as_str()), (witnessed_at, "w.example"));
2294
    // The certificate expired an hour and fifty minutes ago, but covered
2295
    // the integrated time: accepted, and nothing to say.
2296
    assert!(cert.cert.expires < now);
2297
    let mut notes = Vec::new();
2298
    a.authorize_in_time(&p, "origin", &resp.refs[0], &sa, &signer, &lc, &mut notes)
2299
        .unwrap();
2300
    assert!(notes.is_empty(), "{notes:?}");
2301
2302
    // Only the stranger cosigned: no witnessed time, so the earlier rule
2303
    // (the attestation's own time, inside the window), said so.
2304
    let lonely = vec![Integration {
2305
        note: note_of(4, &[("s.example", &stranger, &stranger_sk, 1)]),
2306
        proof: proof4.clone(),
2307
    }];
2308
    let resp = answer(lonely, vec![]);
2309
    let lc = a.check_log(url, None, &resp).unwrap();
2310
    assert!(lc
2311
        .time_of("main")
2312
        .unwrap_err()
2313
        .contains("no witness this user trusts"));
2314
    let mut notes = Vec::new();
2315
    a.authorize_in_time(&p, "origin", &resp.refs[0], &sa, &signer, &lc, &mut notes)
2316
        .unwrap();
2317
    assert!(
2318
        notes.len() == 1 && notes[0].contains("not at a witnessed time"),
2319
        "{notes:?}"
2320
    );
2321
2322
    // A witness listed later under the pinned name with another key is
2323
    // pinned with a note, as a new log key is.
2324
    let resp = answer(
2325
        served.clone(),
2326
        vec![("w.example".into(), stranger.encode())],
2327
    );
2328
    let lc = a.check_log(url, None, &resp).unwrap();
2329
    assert!(
2330
        lc.notes.iter().any(|n| n.contains("another key")),
2331
        "{:?}",
2332
        lc.notes
2333
    );
2334
    assert!(
2335
        lc.time_of("main").is_err(),
2336
        "w's cosignature is by its old key"
2337
    );
2338
    a.check_log(url, None, &answer(served.clone(), listed.clone()))
2339
        .unwrap();
2340
2341
    // An old peer's answer: no log, no witnesses, no integration. Judged
2342
    // as before, silently.
2343
    let mut old = answer(vec![], vec![]);
2344
    old.log = None;
2345
    old.refs[0].logged = None;
2346
    let lc = a.check_log(url, None, &old).unwrap();
2347
    assert!(!lc.kept && lc.notes.is_empty());
2348
    let mut notes = Vec::new();
2349
    a.authorize_in_time(&p, "origin", &old.refs[0], &sa, &signer, &lc, &mut notes)
2350
        .unwrap();
2351
    assert!(notes.is_empty(), "{notes:?}");
2352
2353
    // Judged at given integrated times.
2354
    let at = |secs_after_t0: u64| {
2355
        let mut times = std::collections::HashMap::new();
2356
        times.insert(
2357
            "main".to_string(),
2358
            Ok(Integrated {
2359
                time: (t0 + secs_after_t0 * 1000) / 1000,
2360
                witness: "w.example".into(),
2361
                size: 4,
2362
            }),
2363
        );
2364
        LogCheck {
2365
            kept: true,
2366
            times,
2367
            ..LogCheck::default()
2368
        }
2369
    };
2370
    let judged = |sa: &SignedAttest, lc: &LogCheck| {
2371
        let mut notes = Vec::new();
2372
        a.authorize_in_time(&p, "origin", &old.refs[0], sa, &signer, lc, &mut notes)
2373
            .map(|_| notes)
2374
    };
2375
    // Claimed inside the window, first witnessed an hour later, after
2376
    // the certificate expired: backdated, or held back. Accepted by the
2377
    // earlier rule while logs are new, with both said.
2378
    let notes = judged(&sa, &at(3600)).unwrap();
2379
    assert!(
2380
        notes
2381
            .iter()
2382
            .any(|n| n.contains("had lapsed when witness w.example"))
2383
            && notes
2384
                .iter()
2385
                .any(|n| n.contains("55 minutes before witness")),
2386
        "{notes:?}"
2387
    );
2388
    // Claimed after the certificate expired, but witnessed inside its
2389
    // window: the clock the signer did not choose decides. The gap is
2390
    // still noted.
2391
    let fast = attested(now);
2392
    let notes = judged(&fast, &at(400)).unwrap();
2393
    assert!(
2394
        notes.len() == 1 && notes[0].contains("after witness w.example saw it"),
2395
        "{notes:?}"
2396
    );
2397
    // Claimed and witnessed after it expired: refused, as before.
2398
    assert!(judged(&fast, &at(3600)).is_err());
2399
    // A gap within ten minutes is nothing to note.
2400
    assert!(judged(&sa, &at(500)).unwrap().is_empty());
2401
}
2402
2403
/// Keyless step 5 (oxygenhub#241): an agent's fresh key, certified for a
2404
/// subject the author granted, seals changes in the author's name; with
2405
/// no grant, a stranger's, or one that had ended, it is neither the
2406
/// author nor a delegate.
2407
/// oxygen#135: an owner renews or rotates with every delegation, and a
2408
/// repository may name the newest key as the author; the agent's grant by
2409
/// the earlier key still counts, but not one that key made after.
2410
#[test]
2411
fn a_grant_outlives_its_owner_s_rotation() {
2412
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
2413
    use crate::identity::Scope;
2414
    hermetic();
2415
    let dir = tempfile::tempdir().unwrap();
2416
    let root = dir.path();
2417
    let mut a = Repo::init(&root.join("a"))
2418
        .unwrap()
2419
        .with_home(root.join("home-a"));
2420
    let (old, _) = a
2421
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2422
        .unwrap();
2423
    let (_, old_sk) = a.secret_key().unwrap().unwrap();
2424
    let old_id = a.identity(&old).unwrap();
2425
    let hub_sk = SecretKey::generate();
2426
    let hub = hub_sk.identity("hub", "[email protected]", 1);
2427
    let now = Hlc::now().wall_ms;
2428
    let grant = |from: u64| {
2429
        SignedGrant::sign(
2430
            Grant {
2431
                grantor: old,
2432
                subject: "agent:claude@ada".into(),
2433
                issuer: hub.hash(),
2434
                scope: Scope::CHANGES | Scope::SEAL,
2435
                not_before: from,
2436
                expires: now + 86_400_000,
2437
            },
2438
            &old_id,
2439
            &old_sk,
2440
        )
2441
    };
2442
    let before = grant(now - 60_000);
2443
    let after = grant(now + 60_000);
2444
    let rot = a.renew_identity(None).unwrap();
2445
    assert_ne!(rot.new, old);
2446
    let agent = |name: &str, g: SignedGrant| {
2447
        let mut r = Repo::init(&root.join(name))
2448
            .unwrap()
2449
            .with_home(root.join(format!("home-{name}")));
2450
        let (key, id) = r
2451
            .create_identity(name, "[email protected]", IdentityScope::User)
2452
            .unwrap();
2453
        for i in [&old_id, &rot.identity, &hub] {
2454
            r.store().put_identity(i).unwrap();
2455
        }
2456
        r.set_user_config("author.key", &rot.new.to_hex()).unwrap();
2457
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
2458
        let cert = SignedCertificate::sign(
2459
            Certificate {
2460
                key: id,
2461
                issuer: hub.hash(),
2462
                subject: "agent:claude@ada".into(),
2463
                claims: vec![],
2464
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
2465
                not_before: now - 60_000,
2466
                expires: now + 600_000,
2467
                grant: Some(g),
2468
            },
2469
            &hub,
2470
            &hub_sk,
2471
        );
2472
        r.store().put_certificate(&cert).unwrap();
2473
        write(&root.join(name), "work.txt", b"agent work\n");
2474
        let h = r.commit("work", &[]).unwrap();
2475
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, rot.new);
2476
        r.seal(&[h]).unwrap();
2477
        (r, h)
2478
    };
2479
    let (r, h) = agent("kept", before);
2480
    assert!(
2481
        matches!(
2482
            r.authenticate_change(&h).unwrap(),
2483
            SignatureStatus::Valid { .. }
2484
        ),
2485
        "{:?}",
2486
        r.authenticate_change(&h).unwrap()
2487
    );
2488
    let (r, h) = agent("late", after);
2489
    assert!(
2490
        matches!(r.authenticate_change(&h).unwrap(), SignatureStatus::Invalid(e) if e.contains("neither")),
2491
        "a grant the old key made after the rotation: {:?}",
2492
        r.authenticate_change(&h).unwrap()
2493
    );
2494
}
2495
2496
#[test]
2497
fn a_certified_key_acts_for_its_author_under_a_grant() {
2498
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
2499
    use crate::identity::{Identity, Scope};
2500
    hermetic();
2501
    let dir = tempfile::tempdir().unwrap();
2502
    let root = dir.path();
2503
    let _origin = Repo::init(&root.join("origin")).unwrap();
2504
    let url = root.join("origin").to_string_lossy().to_string();
2505
    let mut a = Repo::clone(&url, &root.join("a"))
2506
        .unwrap()
2507
        .with_home(root.join("home-a"));
2508
    let (ada, _) = a
2509
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2510
        .unwrap();
2511
    write(&root.join("a"), "a.txt", b"a\n");
2512
    a.commit("a", &[]).unwrap();
2513
    a.policy_init().unwrap();
2514
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2515
    let hub_sk = SecretKey::generate();
2516
    let hub = hub_sk.identity("hub", "[email protected]", 1);
2517
    a.policy_grant_subject(
2518
        "agent:claude@ada",
2519
        hub.clone(),
2520
        Scope::CHANGES | Scope::REFS,
2521
        None,
2522
    )
2523
    .unwrap();
2524
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2525
    let (_, ada_sk) = a.secret_key().unwrap().unwrap();
2526
    let ada_id = a.identity(&ada).unwrap();
2527
2528
    let now = Hlc::now().wall_ms;
2529
    let grant = |by: &Identity, sk: &SecretKey, from: u64, to: u64| {
2530
        SignedGrant::sign(
2531
            Grant {
2532
                grantor: by.hash(),
2533
                subject: "agent:claude@ada".into(),
2534
                issuer: hub.hash(),
2535
                scope: Scope::CHANGES | Scope::SEAL,
2536
                not_before: from,
2537
                expires: to,
2538
            },
2539
            by,
2540
            sk,
2541
        )
2542
    };
2543
    // Ada's work as an agent runs it: Ada the author, a fresh key the hub
2544
    // certified (with `g` inside) the signer.
2545
    let agent = |name: &str, g: Option<SignedGrant>| {
2546
        let mut r = Repo::clone(&url, &root.join(name))
2547
            .unwrap()
2548
            .with_home(root.join(format!("home-{name}")));
2549
        let (key, id) = r
2550
            .create_identity(name, "[email protected]", IdentityScope::User)
2551
            .unwrap();
2552
        r.set_user_config("author.key", &ada.to_hex()).unwrap();
2553
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
2554
        let cert = SignedCertificate::sign(
2555
            Certificate {
2556
                key: id,
2557
                issuer: hub.hash(),
2558
                subject: "agent:claude@ada".into(),
2559
                claims: vec![],
2560
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
2561
                not_before: now - 60_000,
2562
                expires: now + 600_000,
2563
                grant: g,
2564
            },
2565
            &hub,
2566
            &hub_sk,
2567
        );
2568
        r.store().put_identity(&hub).unwrap();
2569
        r.store().put_certificate(&cert).unwrap();
2570
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
2571
        let h = r.commit("work", &[]).unwrap();
2572
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, ada);
2573
        (r, key, h)
2574
    };
2575
2576
    let (claude, key, h) = agent(
2577
        "claude",
2578
        Some(grant(&ada_id, &ada_sk, now - 60_000, now + 86_400_000)),
2579
    );
2580
    let r = claude.push("origin", false).unwrap();
2581
    assert!(r.iter().all(|x| x.ok), "{r:?}");
2582
    let host = Repo::open(&root.join("origin")).unwrap();
2583
    assert!(
2584
        matches!(
2585
            host.authenticate_change(&h).unwrap(),
2586
            SignatureStatus::Valid { key: k, sealed: true, name, .. } if k == key && name == "agent:claude@ada"
2587
        ),
2588
        "named by its certificate's subject"
2589
    );
2590
    a.pull("origin").unwrap();
2591
    assert!(matches!(
2592
        a.authenticate_change(&h).unwrap(),
2593
        SignatureStatus::Valid { key: k, .. } if k == key
2594
    ));
2595
2596
    let (none, _, _) = agent("none", None);
2597
    let r = none.push("origin", false).unwrap();
2598
    assert!(r.iter().all(|x| !x.ok), "no grant: {r:?}");
2599
    let mallory_sk = SecretKey::generate();
2600
    let mallory = mallory_sk.identity("Mallory", "[email protected]", 1);
2601
    let (stranger, _, _) = agent(
2602
        "stranger",
2603
        Some(grant(&mallory, &mallory_sk, now - 60_000, now + 600_000)),
2604
    );
2605
    let r = stranger.push("origin", false).unwrap();
2606
    assert!(r.iter().all(|x| !x.ok), "a stranger's grant: {r:?}");
2607
    let (ended, _, eh) = agent(
2608
        "ended",
2609
        Some(grant(&ada_id, &ada_sk, now - 7_200_000, now - 3_600_000)),
2610
    );
2611
    let r = ended.push("origin", false).unwrap();
2612
    assert!(r.iter().all(|x| !x.ok), "an ended grant: {r:?}");
2613
    assert!(matches!(
2614
        ended.authenticate_change(&eh).unwrap(),
2615
        SignatureStatus::Invalid(e) if e.contains("grant did not cover")
2616
    ));
2617
}
2618
2619
#[test]
2620
fn trust_policy_governs_pushes_and_fetches() {
2621
    hermetic();
2622
    let dir = tempfile::tempdir().unwrap();
2623
    let root = dir.path();
2624
    let origin = Repo::init(&root.join("origin")).unwrap();
2625
    let url = root.join("origin").to_string_lossy().to_string();
2626
2627
    // A is the root. Before the policy, an unsigned push from B is fine.
2628
    let mut a = Repo::clone(&url, &root.join("a"))
2629
        .unwrap()
2630
        .with_home(root.join("home-a"));
2631
    let (key_a, _) = a
2632
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2633
        .unwrap();
2634
    let mut b = Repo::clone(&url, &root.join("b"))
2635
        .unwrap()
2636
        .with_home(root.join("home-b"));
2637
    write(&root.join("b"), "b.txt", b"b\n");
2638
    b.commit("unsigned before policy", &[]).unwrap();
2639
    assert!(b.push("origin", false).unwrap()[0].ok);
2640
    origin.refresh().unwrap();
2641
2642
    // A creates the policy and pushes it; origin now enforces it.
2643
    write(&root.join("a"), "a.txt", b"a\n");
2644
    a.commit("a", &[]).unwrap();
2645
    let sp = a.policy_init().unwrap();
2646
    assert_eq!(sp.policy.serial, 1);
2647
    a.pull("origin").unwrap();
2648
    let results = a.push("origin", false).unwrap();
2649
    origin.refresh().unwrap();
2650
    assert!(results.iter().all(|r| r.ok), "{results:?}");
2651
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
2652
2653
    // B pulls the policy. Without an identity B cannot push at all.
2654
    b.pull("origin").unwrap();
2655
    assert!(
2656
        b.current_policy().unwrap().is_some(),
2657
        "the policy arrived with the fetch"
2658
    );
2659
    assert!(b.push("origin", false).is_err());
2660
    // With an identity the policy does not list, the push is rejected by origin.
2661
    let (key_b, id_b) = b
2662
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2663
        .unwrap();
2664
    write(&root.join("b"), "b.txt", b"b2\n");
2665
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
2666
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
2667
    let r = b.push("origin", false).unwrap();
2668
    origin.refresh().unwrap();
2669
    assert!(
2670
        !r[0].ok && r[0].reason.contains("may not update"),
2671
        "{:?}",
2672
        r
2673
    );
2674
2675
    // A grants B (identity handed over as a file) and publishes the policy.
2676
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
2677
    assert_eq!(sp.policy.serial, 2);
2678
    let r = a.push("origin", false).unwrap();
2679
    origin.refresh().unwrap();
2680
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
2681
    // B must fetch the new policy before pushing.
2682
    assert!(b
2683
        .push("origin", false)
2684
        .unwrap_or_else(|e| vec![RefResult {
2685
            name: "main".into(),
2686
            ok: false,
2687
            reason: e.to_string()
2688
        }])
2689
        .iter()
2690
        .all(|x| !x.ok));
2691
    b.pull("origin").unwrap();
2692
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
2693
    let r = b.push("origin", false).unwrap();
2694
    origin.refresh().unwrap();
2695
    assert!(r[0].ok, "{:?}", r);
2696
    // Origin verified B's change under the policy.
2697
    let heads = origin.bookmark_heads().unwrap();
2698
    for h in &heads {
2699
        let c = origin.store().get_change(h).unwrap();
2700
        if c.author == key_b {
2701
            origin
2702
                .change_allowed(
2703
                    h,
2704
                    &origin.current_policy().unwrap().unwrap().1.policy,
2705
                    "main",
2706
                )
2707
                .unwrap();
2708
        }
2709
    }
2710
2711
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
2712
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
2713
    forged.serial = 3;
2714
    forged.roots = vec![key_b];
2715
    let fh = forged.hash();
2716
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
2717
    let forged = SignedPolicy {
2718
        policy: forged,
2719
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
2720
    };
2721
    let r = origin
2722
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
2723
        .unwrap();
2724
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
2725
    let stale = a.current_policy().unwrap().unwrap().1;
2726
    let mut old = stale.clone();
2727
    old.policy.serial = 1;
2728
    let r = origin
2729
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
2730
        .unwrap();
2731
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
2732
2733
    // A revokes B; after B pulls the policy, B's pushes are refused again.
2734
    a.pull("origin").unwrap();
2735
    a.policy_revoke(&key_b).unwrap();
2736
    let r = a.push("origin", false).unwrap();
2737
    origin.refresh().unwrap();
2738
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
2739
    b.pull("origin").unwrap();
2740
    write(&root.join("b"), "b.txt", b"b3\n");
2741
    b.commit("b3", &[]).unwrap();
2742
    let r = b.push("origin", false).unwrap();
2743
    origin.refresh().unwrap();
2744
    assert!(!r[0].ok, "{:?}", r);
2745
2746
    // A clone by a third party receives and verifies everything.
2747
    let c = Repo::clone(&url, &root.join("c"))
2748
        .unwrap()
2749
        .with_home(root.join("home-c"));
2750
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
2751
    assert!(c
2752
        .current_policy()
2753
        .unwrap()
2754
        .unwrap()
2755
        .1
2756
        .policy
2757
        .roots
2758
        .contains(&key_a));
2759
    assert!(!c.snapshot("status").unwrap().changed);
2760
}
2761
2762
/// oxygen#66: a gc says what it is doing, phase by phase.
2763
#[test]
2764
fn gc_reports_its_phases() {
2765
    hermetic();
2766
    let dir = tempfile::tempdir().unwrap();
2767
    let repo = Repo::init(dir.path()).unwrap();
2768
    for i in 0..3 {
2769
        write(
2770
            dir.path(),
2771
            &format!("f{i}.txt"),
2772
            format!("{i}\n").as_bytes(),
2773
        );
2774
        repo.commit(&format!("c{i}"), &[]).unwrap();
2775
    }
2776
    let mut phases = Vec::new();
2777
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
2778
        .unwrap();
2779
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
2780
    assert!(
2781
        phases.iter().any(|p| p.starts_with("pruning")),
2782
        "{phases:?}"
2783
    );
2784
    assert!(
2785
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
2786
        "{phases:?}"
2787
    );
2788
    assert!(
2789
        phases
2790
            .iter()
2791
            .any(|p| p.starts_with("writing the index of ")),
2792
        "{phases:?}"
2793
    );
2794
}
2795
2796
#[test]
2797
fn gc_packs_objects_and_history_still_works() {
2798
    hermetic();
2799
    let dir = tempfile::tempdir().unwrap();
2800
    let root = dir.path();
2801
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2802
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2803
        .unwrap();
2804
    repo.set_user_config("core.sign", "change").unwrap();
2805
    write(root, "a.txt", b"one\n");
2806
    let h1 = repo.commit("one", &[]).unwrap();
2807
    write(root, "a.txt", b"two\n");
2808
    write(root, "big.bin", &vec![0u8; 100_000]);
2809
    let h2 = repo.commit("two", &[]).unwrap();
2810
    // Several snapshots leave superseded working-copy versions behind.
2811
    for i in 0..5 {
2812
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
2813
        repo.snapshot("status").unwrap();
2814
    }
2815
    write(root, "a.txt", b"two\n");
2816
    repo.snapshot("status").unwrap();
2817
    let before = repo.store().list().unwrap();
2818
    assert!(repo.store().loose_count().unwrap() > 0);
2819
2820
    // With the default retention every operation's view is a root: nothing prunes.
2821
    let r = repo.gc(true).unwrap();
2822
    assert_eq!(r.packed.objects, before.len());
2823
    assert_eq!(r.pruned.objects, 0);
2824
    assert_eq!(repo.store().loose_count().unwrap(), 0);
2825
    assert_eq!(repo.store().list().unwrap(), before);
2826
2827
    // With zero retention only the current view is a root: superseded
2828
    // working copies go, everything reachable stays.
2829
    repo.config.set("core.op-retention", "0").unwrap();
2830
    repo.save_config().unwrap();
2831
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
2832
    let r = repo.gc(true).unwrap();
2833
    assert!(r.pruned.objects >= 5, "{r:?}");
2834
    let after = repo.store().list().unwrap();
2835
    assert!(after.len() < before.len());
2836
    assert!(after.contains(&h1) && after.contains(&h2));
2837
    for (_, op) in repo.op_log().unwrap() {
2838
        assert!(!op.command.is_empty(), "operation objects are all kept");
2839
    }
2840
    // Everything still works from the pruned, packed store.
2841
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
2842
    assert!(matches!(
2843
        repo.verify_change(&h2).unwrap(),
2844
        SignatureStatus::Valid { .. }
2845
    ));
2846
    assert_eq!(repo.log().unwrap().len(), 3);
2847
    repo.checkout(&[h1], false, "checkout").unwrap();
2848
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
2849
    repo.checkout(&[h2], false, "checkout").unwrap();
2850
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
2851
    assert!(!repo.snapshot("status").unwrap().changed);
2852
    // Grace period defers pruning of young garbage.
2853
    write(root, "a.txt", b"three\n");
2854
    repo.commit("three", &[]).unwrap();
2855
    let r = repo.gc(false).unwrap();
2856
    assert_eq!(r.pruned.objects, 0);
2857
    assert!(r.pruned.deferred > 0);
2858
    let r = repo.gc(true).unwrap();
2859
    assert!(r.pruned.objects > 0);
2860
    assert_eq!(repo.log().unwrap().len(), 4);
2861
    // Restoring the default retention makes the old views roots again; the
2862
    // working copies they name were pruned, which gc tolerates.
2863
    repo.config.set("core.op-retention", "90").unwrap();
2864
    repo.save_config().unwrap();
2865
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2866
    let r = repo.gc(false).unwrap();
2867
    assert_eq!(r.pruned.objects, 0);
2868
    assert_eq!(repo.log().unwrap().len(), 4);
2869
}
2870
2871
#[test]
2872
fn describe_amend_abandon_heads() {
2873
    hermetic();
2874
    let dir = tempfile::tempdir().unwrap();
2875
    let root = dir.path();
2876
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2877
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2878
        .unwrap();
2879
    repo.set_user_config("core.sign", "change").unwrap();
2880
    write(root, "a.txt", b"one\n");
2881
    let h1 = repo.commit("first", &[]).unwrap();
2882
    write(root, "a.txt", b"one\ntwo\n");
2883
    let h2 = repo.commit("secnod", &[]).unwrap();
2884
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
2885
2886
    // describe: same ChangeId, new hash, bookmark and working copy follow.
2887
    let h2b = repo.describe(&h2, "second").unwrap();
2888
    assert_ne!(h2b, h2);
2889
    let c = repo.store().get_change(&h2b).unwrap();
2890
    assert_eq!(
2891
        (c.change_id, c.message.as_str(), c.deps.clone()),
2892
        (id2, "second", vec![h1])
2893
    );
2894
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
2895
    assert!(matches!(
2896
        repo.verify_change(&h2b).unwrap(),
2897
        SignatureStatus::Valid { .. }
2898
    ));
2899
    let s = repo.snapshot("status").unwrap();
2900
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
2901
    assert_eq!(
2902
        repo.resolve_change(&id2.short(8)).unwrap(),
2903
        h2b,
2904
        "the old object is no longer reachable from the log"
2905
    );
2906
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
2907
    let h1b = repo.describe(&h1, "first, described").unwrap();
2908
    assert_ne!(h1b, h1);
2909
    let heads = repo.bookmark_heads().unwrap();
2910
    assert_eq!(heads.len(), 1);
2911
    let top = repo.store().get_change(&heads[0]).unwrap();
2912
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
2913
    assert!(
2914
        matches!(
2915
            repo.verify_change(&heads[0]).unwrap(),
2916
            SignatureStatus::Valid { .. }
2917
        ),
2918
        "rewritten own change is re-signed"
2919
    );
2920
    let (_, wc) = repo.working_copy().unwrap();
2921
    assert_eq!(
2922
        wc.deps,
2923
        vec![heads[0]],
2924
        "the working copy follows the rewrite"
2925
    );
2926
    assert!(!repo.snapshot("status").unwrap().changed);
2927
    let snap = repo.load_state(&heads).unwrap().materialize();
2928
    assert!(
2929
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
2930
    );
2931
2932
    // amend: fold an edit into the head; the result is one change from h1.
2933
    write(root, "a.txt", b"one\ntwo\nthree\n");
2934
    write(root, "b.txt", b"b\n");
2935
    let h2c = repo.amend(None).unwrap();
2936
    let c = repo.store().get_change(&h2c).unwrap();
2937
    assert_eq!(c.change_id, id2);
2938
    assert_eq!(c.message, "second");
2939
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
2940
    assert_eq!(
2941
        repo.log().unwrap().len(),
2942
        3,
2943
        "working copy, amended head, first"
2944
    );
2945
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
2946
    assert!(
2947
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
2948
    );
2949
    assert!(snap.files.contains_key("b.txt"));
2950
    assert!(!repo.snapshot("status").unwrap().changed);
2951
    assert!(
2952
        repo.amend(None).is_err(),
2953
        "clean working copy and no message"
2954
    );
2955
    let h2d = repo.amend(Some("second, amended")).unwrap();
2956
    assert_eq!(
2957
        repo.store().get_change(&h2d).unwrap().message,
2958
        "second, amended"
2959
    );
2960
2961
    // abandon: the head goes, its content stays as uncommitted work.
2962
    repo.abandon(&h2d).unwrap();
2963
    assert_eq!(
2964
        repo.bookmark_heads().unwrap(),
2965
        vec![h1b],
2966
        "the described first change is the head again"
2967
    );
2968
    let s = repo.snapshot("status").unwrap();
2969
    let paths: Vec<_> = s
2970
        .statuses
2971
        .iter()
2972
        .map(|p| (p.path.as_str(), p.status))
2973
        .collect();
2974
    assert_eq!(
2975
        paths,
2976
        vec![
2977
            ("a.txt", ChangeStatus::Modified),
2978
            ("b.txt", ChangeStatus::Added)
2979
        ]
2980
    );
2981
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
2982
    let h3 = repo.commit("recommitted", &[]).unwrap();
2983
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
2984
    // undo brings the abandoned head back.
2985
    repo.undo().unwrap();
2986
    repo.undo().unwrap();
2987
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
2988
2989
    // Abandoning a non-head whose dependent references its atoms reifies
2990
    // the references (here: a.txt vanishes with it, so the dependent's edit
2991
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
2992
    let base = repo.bookmark_heads().unwrap()[0];
2993
    let base_change = repo.store().get_change(&base).unwrap();
2994
    let h1_now = base_change.deps[0];
2995
    let notes = repo.abandon(&h1_now).unwrap();
2996
    assert!(
2997
        !notes.is_empty(),
2998
        "the dependent's edit of a.txt was reified"
2999
    );
3000
    let heads = repo.bookmark_heads().unwrap();
3001
    let after = repo.load_state(&heads).unwrap().materialize();
3002
    assert!(
3003
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
3004
        "{:?}",
3005
        after.files.keys()
3006
    );
3007
    repo.undo().unwrap();
3008
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
3009
    write(root, "c.txt", b"c\n");
3010
    let hc = repo.commit("c", &[]).unwrap();
3011
    write(root, "d.txt", b"d\n");
3012
    let hd = repo.commit("d", &[hc]).unwrap();
3013
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
3014
    repo.abandon(&hc).unwrap();
3015
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
3016
    assert!(!heads.contains(&hc));
3017
    let d_now = heads
3018
        .iter()
3019
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
3020
        .copied()
3021
        .unwrap();
3022
    assert!(
3023
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
3024
        "d inherited c's (empty) dependencies"
3025
    );
3026
    let s = repo.snapshot("status").unwrap();
3027
    assert_eq!(
3028
        s.statuses
3029
            .iter()
3030
            .map(|p| p.path.as_str())
3031
            .collect::<Vec<_>>(),
3032
        vec!["c.txt"],
3033
        "c's content is now uncommitted work"
3034
    );
3035
}
3036
3037
#[test]
3038
fn git_export_mirrors_history() {
3039
    hermetic();
3040
    if std::process::Command::new("git")
3041
        .arg("--version")
3042
        .output()
3043
        .is_err()
3044
    {
3045
        eprintln!("git not installed; skipping");
3046
        return;
3047
    }
3048
    let dir = tempfile::tempdir().unwrap();
3049
    let root = dir.path();
3050
    let mut repo = Repo::init(&root.join("r"))
3051
        .unwrap()
3052
        .with_home(root.join("home"));
3053
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
3054
        .unwrap();
3055
    let r = root.join("r");
3056
    write(&r, "README.md", b"hello\n");
3057
    write(&r, "src/main.rs", b"fn main() {}\n");
3058
    let h1 = repo.commit("first", &[]).unwrap();
3059
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
3060
    write(&r, "logo.png", b"\x89PNG\0\0");
3061
    let h2 = repo.commit("second", &[]).unwrap();
3062
3063
    let git_dir = root.join("mirror.git");
3064
    let rep = repo.git_export(&git_dir).unwrap();
3065
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
3066
    let git = |args: &[&str]| -> String {
3067
        let out = std::process::Command::new("git")
3068
            .arg("-C")
3069
            .arg(&git_dir)
3070
            .args(args)
3071
            .output()
3072
            .unwrap();
3073
        assert!(
3074
            out.status.success(),
3075
            "{}",
3076
            String::from_utf8_lossy(&out.stderr)
3077
        );
3078
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3079
    };
3080
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
3081
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
3082
    assert_eq!(git(&["show", "main:README.md"]), "hello");
3083
    let body = git(&["log", "-1", "--format=%B", "main"]);
3084
    assert!(
3085
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
3086
        "{body}"
3087
    );
3088
    assert!(body.contains("Change-Id: "), "{body}");
3089
    assert_eq!(
3090
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
3091
        "Ada Lovelace <[email protected]>"
3092
    );
3093
    assert_eq!(
3094
        git(&["ls-tree", "--name-only", "main"]),
3095
        "README.md\nlogo.png\nsrc"
3096
    );
3097
3098
    // Re-export is incremental.
3099
    let rep = repo.git_export(&git_dir).unwrap();
3100
    assert_eq!((rep.exported, rep.skipped), (0, 2));
3101
3102
    // An independent change makes two heads; the next state is one more
3103
    // commit on the linear branch whose tree is the union.
3104
    repo.checkout(&[h1], false, "checkout").unwrap();
3105
    write(&r, "other.txt", b"o\n");
3106
    let h3 = repo.commit("third", &[]).unwrap();
3107
    let rep = repo.git_export(&git_dir).unwrap();
3108
    assert_eq!((rep.exported, rep.heads), (1, 2));
3109
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
3110
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
3111
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
3112
    assert_eq!(git(&["show", "main:other.txt"]), "o");
3113
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
3114
    assert_eq!(
3115
        git(&["ls-tree", "--name-only", "main"]),
3116
        "README.md\nlogo.png\nother.txt\nsrc"
3117
    );
3118
    let body = git(&["log", "-1", "--format=%B", "main"]);
3119
    assert!(
3120
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
3121
        "{body}"
3122
    );
3123
    // A rewrite is a new state whose one new change is the rewritten one.
3124
    repo.describe(&h3, "third, described").unwrap();
3125
    let rep = repo.git_export(&git_dir).unwrap();
3126
    assert_eq!(rep.exported, 1);
3127
    assert_eq!(
3128
        git(&["log", "-1", "--format=%s", "main"]),
3129
        "third, described"
3130
    );
3131
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
3132
    let _ = h2;
3133
}
3134
3135
#[test]
3136
fn git_import_reproduces_trees() {
3137
    git_import_reproduces_trees_with(None);
3138
}
3139
3140
/// The same import with every merge rendered in batches of one file
3141
/// (oxygen#25): what a merge onto a base of thousands of files takes.
3142
#[test]
3143
fn git_import_reproduces_trees_in_batches() {
3144
    git_import_reproduces_trees_with(Some(1));
3145
}
3146
3147
fn git_import_reproduces_trees_with(batch: Option<usize>) {
3148
    crate::repo::git::set_merge_batch_for_tests(batch);
3149
    hermetic();
3150
    if std::process::Command::new("git")
3151
        .arg("--version")
3152
        .output()
3153
        .is_err()
3154
    {
3155
        eprintln!("git not installed; skipping");
3156
        return;
3157
    }
3158
    let dir = tempfile::tempdir().unwrap();
3159
    let root = dir.path();
3160
    let g = root.join("src.git");
3161
    fs::create_dir_all(&g).unwrap();
3162
    let git = |args: &[&str]| -> String {
3163
        let out = std::process::Command::new("git")
3164
            .arg("-C")
3165
            .arg(&g)
3166
            .args([
3167
                "-c",
3168
                "user.name=Grace",
3169
                "-c",
3170
                "[email protected]",
3171
                "-c",
3172
                "commit.gpgsign=false",
3173
            ])
3174
            .args(args)
3175
            .output()
3176
            .unwrap();
3177
        assert!(
3178
            out.status.success(),
3179
            "git {args:?}: {}",
3180
            String::from_utf8_lossy(&out.stderr)
3181
        );
3182
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3183
    };
3184
    git(&["init", "-q", "-b", "main"]);
3185
    write(&g, "README.md", b"# Hi\n");
3186
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
3187
    git(&["add", "."]);
3188
    git(&["commit", "-q", "-m", "initial"]);
3189
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
3190
    write(&g, "run.sh", b"#!/bin/sh\n");
3191
    #[cfg(unix)]
3192
    {
3193
        use std::os::unix::fs::PermissionsExt;
3194
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
3195
    }
3196
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
3197
    git(&["add", "."]);
3198
    git(&[
3199
        "commit",
3200
        "-q",
3201
        "-m",
3202
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
3203
    ]);
3204
    // A branch that edits README, merged back with a conflict-free merge.
3205
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
3206
    write(&g, "README.md", b"# Hi\n\nMore.\n");
3207
    git(&["commit", "-q", "-am", "readme"]);
3208
    git(&["checkout", "-q", "main"]);
3209
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
3210
    // A branch from the initial commit inserting at the same place as
3211
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
3212
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
3213
    git(&["checkout", "-q", "-b", "clash", &initial]);
3214
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
3215
    git(&["commit", "-q", "-am", "clash"]);
3216
    git(&["checkout", "-q", "main"]);
3217
    // Expected to stop at the conflict, so its status is ignored; the
3218
    // identity is passed as for every other git call here, or a machine
3219
    // without one refuses to start the merge at all.
3220
    let _ = std::process::Command::new("git")
3221
        .arg("-C")
3222
        .arg(&g)
3223
        .args([
3224
            "-c",
3225
            "user.name=Grace",
3226
            "-c",
3227
            "[email protected]",
3228
            "merge",
3229
            "-q",
3230
            "clash",
3231
        ])
3232
        .output();
3233
    assert!(
3234
        g.join(".git/MERGE_HEAD").exists(),
3235
        "the clash merge stopped at its conflict"
3236
    );
3237
    write(
3238
        &g,
3239
        "src/lib.rs",
3240
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
3241
    );
3242
    git(&["add", "."]);
3243
    git(&["commit", "-q", "-m", "resolve clash"]);
3244
    git(&["rm", "-q", "logo.png"]);
3245
    git(&["commit", "-q", "-m", "drop logo"]);
3246
    // A rename with a small edit is imported as a move of the same node.
3247
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
3248
    write(
3249
        &g,
3250
        "src/lib2.rs",
3251
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
3252
    );
3253
    git(&["add", "."]);
3254
    git(&["commit", "-q", "-m", "rename lib"]);
3255
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
3256
    // run.sh is the same as in the first parent's tree, but the merged
3257
    // change touched it, so the importer must compare it, not skip it.
3258
    git(&["checkout", "-q", "-b", "discarded"]);
3259
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
3260
    git(&["commit", "-q", "-am", "discarded edit"]);
3261
    git(&["checkout", "-q", "main"]);
3262
    git(&[
3263
        "merge",
3264
        "-q",
3265
        "-s",
3266
        "ours",
3267
        "-m",
3268
        "merge discarded, keeping ours",
3269
        "discarded",
3270
    ]);
3271
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
3272
3273
    let dest = root.join("oxy");
3274
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3275
    let rep = repo.import_git(&g, "main").unwrap();
3276
    assert_eq!(rep.commits, expected_count);
3277
    assert_eq!(rep.merges, 3);
3278
    assert_eq!(
3279
        fs::read(dest.join("run.sh")).unwrap(),
3280
        b"#!/bin/sh\n",
3281
        "the ours merge kept main's run.sh"
3282
    );
3283
    let v = repo.verify_git_import(&g, "main").unwrap();
3284
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
3285
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
3286
    // The working copy equals the Git tree at main.
3287
    assert_eq!(
3288
        fs::read(dest.join("src/lib2.rs")).unwrap(),
3289
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
3290
    );
3291
    assert!(!dest.join("src/lib.rs").exists());
3292
    assert_eq!(
3293
        fs::read(dest.join("README.md")).unwrap(),
3294
        b"# Hi\n\nMore.\n"
3295
    );
3296
    assert!(!dest.join("logo.png").exists());
3297
    #[cfg(unix)]
3298
    {
3299
        use std::os::unix::fs::PermissionsExt;
3300
        assert!(
3301
            fs::metadata(dest.join("run.sh"))
3302
                .unwrap()
3303
                .permissions()
3304
                .mode()
3305
                & 0o111
3306
                != 0
3307
        );
3308
    }
3309
    assert!(
3310
        !repo.snapshot("status").unwrap().changed,
3311
        "clean after import"
3312
    );
3313
    let heads = repo.bookmark_heads().unwrap();
3314
    let st = repo.load_state(&heads).unwrap();
3315
    assert!(!st.materialize().is_conflicted());
3316
    assert_eq!(st.len(), expected_count);
3317
    let tip = repo
3318
        .log()
3319
        .unwrap()
3320
        .into_iter()
3321
        .find(|e| e.change.message.starts_with("rename lib"))
3322
        .unwrap();
3323
    let c = repo.store().get_change(&tip.hash).unwrap();
3324
    assert!(
3325
        c.tree_ops
3326
            .iter()
3327
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
3328
        "{:?}",
3329
        c.tree_ops
3330
    );
3331
    assert!(!c
3332
        .tree_ops
3333
        .iter()
3334
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
3335
    // Messages carry Git trailers; the Change-Id trailer was honoured.
3336
    let log = repo.log().unwrap();
3337
    let second = log
3338
        .iter()
3339
        .find(|e| e.change.message.starts_with("second"))
3340
        .unwrap();
3341
    assert_eq!(
3342
        second.change.change_id,
3343
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
3344
    );
3345
    assert!(second
3346
        .change
3347
        .message
3348
        .contains("Git-Author: Grace <[email protected]>"));
3349
    let resolve = log
3350
        .iter()
3351
        .find(|e| e.change.message.starts_with("resolve clash"))
3352
        .unwrap();
3353
    assert_eq!(
3354
        resolve.change.kind,
3355
        ChangeKind::Resolution,
3356
        "a conflicting Git merge becomes a resolution"
3357
    );
3358
    // Re-importing into another fresh repository gives the same ChangeIds.
3359
    let repo2 = Repo::init(&root.join("oxy2"))
3360
        .unwrap()
3361
        .with_home(root.join("home"));
3362
    repo2.import_git(&g, "main").unwrap();
3363
    // New nodes' identifiers derive from the commit (spec §23), so the
3364
    // re-import is not just the same ChangeIds but the same changes.
3365
    assert_eq!(
3366
        repo2.bookmark_heads().unwrap(),
3367
        repo.bookmark_heads().unwrap()
3368
    );
3369
    let ids: BTreeSet<ChangeId> = repo
3370
        .log()
3371
        .unwrap()
3372
        .iter()
3373
        .filter(|e| !e.is_working_copy)
3374
        .map(|e| e.change.change_id)
3375
        .collect();
3376
    let ids2: BTreeSet<ChangeId> = repo2
3377
        .log()
3378
        .unwrap()
3379
        .iter()
3380
        .filter(|e| !e.is_working_copy)
3381
        .map(|e| e.change.change_id)
3382
        .collect();
3383
    assert_eq!(ids, ids2);
3384
    // Round trip back out to Git reproduces the tip tree.
3385
    let mirror = root.join("mirror.git");
3386
    repo.git_export(&mirror).unwrap();
3387
    let out = std::process::Command::new("git")
3388
        .arg("-C")
3389
        .arg(&mirror)
3390
        .args(["show", "main:src/lib2.rs"])
3391
        .output()
3392
        .unwrap();
3393
    assert_eq!(
3394
        String::from_utf8_lossy(&out.stdout),
3395
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
3396
    );
3397
    let out = std::process::Command::new("git")
3398
        .arg("-C")
3399
        .arg(&mirror)
3400
        .args(["show", "main:src/lib.rs"])
3401
        .output()
3402
        .unwrap();
3403
    assert!(
3404
        !out.status.success(),
3405
        "the old path is gone from the export"
3406
    );
3407
}
3408
3409
#[test]
3410
fn checkpoints_accelerate_loading_and_stay_correct() {
3411
    hermetic();
3412
    let dir = tempfile::tempdir().unwrap();
3413
    let root = dir.path();
3414
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3415
    repo.config.set("core.checkpoint-interval", "5").unwrap();
3416
    repo.save_config().unwrap();
3417
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
3418
    let mut hashes = Vec::new();
3419
    for i in 0..12 {
3420
        write(
3421
            root,
3422
            "a.txt",
3423
            format!(
3424
                "{}\n",
3425
                (0..=i)
3426
                    .map(|k| k.to_string())
3427
                    .collect::<Vec<_>>()
3428
                    .join("\n")
3429
            )
3430
            .as_bytes(),
3431
        );
3432
        write(root, &format!("f{i}.txt"), b"x\n");
3433
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
3434
    }
3435
    let (_, cp) = repo
3436
        .latest_checkpoint("main")
3437
        .unwrap()
3438
        .expect("automatic checkpoint");
3439
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
3440
    // Loading through the checkpoint equals loading everything.
3441
    let heads = repo.bookmark_heads().unwrap();
3442
    let fast = repo.load_state(&heads).unwrap();
3443
    let full = repo.load_state_full(&heads).unwrap();
3444
    assert_eq!(fast.len(), full.len());
3445
    assert_eq!(fast.heads(), full.heads());
3446
    let (a, b) = (fast.materialize(), full.materialize());
3447
    assert_eq!(
3448
        a.files.keys().collect::<Vec<_>>(),
3449
        b.files.keys().collect::<Vec<_>>()
3450
    );
3451
    for (p, f) in &a.files {
3452
        assert_eq!(f.content, b.files[p].content, "{p}");
3453
    }
3454
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
3455
    // A head set that does not contain the checkpoint's heads falls back.
3456
    assert!(repo
3457
        .load_state_checkpointed(&[hashes[0]])
3458
        .unwrap()
3459
        .is_none());
3460
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
3461
    // Everything else keeps working on top of the checkpoint.
3462
    assert!(!repo.snapshot("status").unwrap().changed);
3463
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
3464
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
3465
    let (r, n, bytes) = repo.checkpoint().unwrap();
3466
    assert!(n >= 12 && bytes > 0);
3467
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
3468
    write(root, "a.txt", b"after\n");
3469
    let h_after = repo.commit("after", &[]).unwrap();
3470
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
3471
    assert!(st.contains(&h_after));
3472
    assert!(
3473
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
3474
    );
3475
    assert_eq!(repo.log().unwrap().len(), 14);
3476
    // Checkpoints survive gc.
3477
    repo.gc(true).unwrap();
3478
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
3479
    assert!(repo
3480
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
3481
        .unwrap()
3482
        .is_some());
3483
}
3484
3485
#[test]
3486
fn quick_status_for_prompts() {
3487
    hermetic();
3488
    let dir = tempfile::tempdir().unwrap();
3489
    let root = dir.path();
3490
    let origin = Repo::init(&root.join("origin")).unwrap();
3491
    let url = root.join("origin").to_string_lossy().to_string();
3492
    let a = Repo::clone(&url, &root.join("a"))
3493
        .unwrap()
3494
        .with_home(root.join("home"));
3495
    let ops_before = a.op_log().unwrap().len();
3496
    let info = a.quick_status().unwrap();
3497
    assert_eq!(
3498
        (
3499
            info.bookmark.as_str(),
3500
            info.heads,
3501
            info.dirty,
3502
            info.conflicted,
3503
            info.ahead,
3504
            info.behind
3505
        ),
3506
        ("main", 0, false, false, Some(0), Some(0))
3507
    );
3508
    write(&root.join("a"), "f.txt", b"f\n");
3509
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
3510
    assert_eq!(
3511
        a.op_log().unwrap().len(),
3512
        ops_before,
3513
        "quick_status records nothing"
3514
    );
3515
    // A snapshotted but uncommitted change is still dirty.
3516
    a.snapshot("status").unwrap();
3517
    assert!(a.quick_status().unwrap().dirty);
3518
    a.commit("f", &[]).unwrap();
3519
    let info = a.quick_status().unwrap();
3520
    assert!(!info.dirty, "clean right after a commit");
3521
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
3522
    assert_eq!(
3523
        info.format("%b %c%d%x%A%D"),
3524
        format!("main {}+1", info.change_id)
3525
    );
3526
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
3527
    // Touching a file without changing it is not dirty; changing content of
3528
    // the same size is.
3529
    let p = root.join("a/f.txt");
3530
    let content = fs::read(&p).unwrap();
3531
    fs::write(&p, &content).unwrap();
3532
    assert!(!a.quick_status().unwrap().dirty);
3533
    fs::write(&p, b"g\n").unwrap();
3534
    assert!(a.quick_status().unwrap().dirty);
3535
    fs::write(&p, b"f\n").unwrap();
3536
    // Push, then a second clone commits and pushes: we are behind.
3537
    assert!(a.push("origin", false).unwrap()[0].ok);
3538
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
3539
    let b = Repo::clone(&url, &root.join("b"))
3540
        .unwrap()
3541
        .with_home(root.join("home-b"));
3542
    write(&root.join("b"), "g.txt", b"g\n");
3543
    b.commit("g", &[]).unwrap();
3544
    b.push("origin", false).unwrap();
3545
    a.fetch("origin").unwrap();
3546
    let info = a.quick_status().unwrap();
3547
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
3548
    assert_eq!(info.format("%A%D"), "-1");
3549
    let _ = origin;
3550
}
3551
3552
#[test]
3553
fn lazy_blobs_are_fetched_on_first_read() {
3554
    hermetic();
3555
    let dir = tempfile::tempdir().unwrap();
3556
    let root = dir.path();
3557
    let origin_dir = root.join("origin");
3558
    let origin = Repo::init(&origin_dir)
3559
        .unwrap()
3560
        .with_home(root.join("home"));
3561
    let url = origin_dir.to_string_lossy().to_string();
3562
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
3563
    write(&origin_dir, "big.bin", &big);
3564
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
3565
    write(&origin_dir, "t.txt", b"t\n");
3566
    let h = origin.commit("blobs", &[]).unwrap();
3567
    let big_ref = Repo::blob_ref(&big);
3568
3569
    // Fetch only (no checkout) with a filter: the big blob stays absent.
3570
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
3571
        .unwrap()
3572
        .with_home(root.join("home"));
3573
    let a = {
3574
        let mut a = a;
3575
        a.config.set("remote.origin.url", &url).unwrap();
3576
        a.config.set("filter.max-blob", "100K").unwrap();
3577
        a.save_config().unwrap();
3578
        a
3579
    };
3580
    assert_eq!(a.config.max_blob, Some(100 * 1024));
3581
    a.fetch("origin").unwrap();
3582
    assert!(a.store().has(&h));
3583
    assert!(!a.store().has(&big_ref), "withheld");
3584
    assert!(
3585
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
3586
        "small blob came along"
3587
    );
3588
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
3589
3590
    // status and commit do not need it: adopt the state, edit a text file, commit.
3591
    let (op_ref, op) = a.head_op().unwrap();
3592
    let mut view = op.view.clone();
3593
    view.bookmarks.insert(
3594
        "main".into(),
3595
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
3596
    );
3597
    a.record_op(&[op_ref], "adopt", view).unwrap();
3598
    // Checkout reads the blob lazily, which fetches it.
3599
    a.checkout(&[h], true, "checkout").unwrap();
3600
    assert!(a.store().has(&big_ref), "fetched on first read");
3601
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
3602
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
3603
    write(&root.join("a"), "t.txt", b"t2\n");
3604
    a.commit("text edit", &[]).unwrap();
3605
3606
    // clone --max-blob records the filter; the checkout fetches lazily.
3607
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
3608
    assert_eq!(b.config.max_blob, Some(1024));
3609
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
3610
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
3611
    assert!(parse_size("lots").is_err());
3612
}
3613
3614
#[test]
3615
fn sparse_checkout_materializes_only_chosen_paths() {
3616
    hermetic();
3617
    let dir = tempfile::tempdir().unwrap();
3618
    let root = dir.path();
3619
    let origin_dir = root.join("origin");
3620
    let origin = Repo::init(&origin_dir)
3621
        .unwrap()
3622
        .with_home(root.join("home"));
3623
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
3624
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
3625
    write(&origin_dir, "docs/guide.md", b"# guide\n");
3626
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
3627
    write(&origin_dir, "docs/logo.png", &logo);
3628
    write(&origin_dir, "README.md", b"# top\n");
3629
    let h1 = origin.commit("tree", &[]).unwrap();
3630
    let url = origin_dir.to_string_lossy().to_string();
3631
3632
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
3633
        .unwrap()
3634
        .with_home(root.join("home"));
3635
    assert_eq!(a.config.sparse_paths, vec!["src"]);
3636
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
3637
    assert!(root.join("a/src/main.rs").exists());
3638
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
3639
    assert!(
3640
        !a.store().has(&Repo::blob_ref(&logo)),
3641
        "out-of-scope blob never fetched"
3642
    );
3643
    assert!(
3644
        !a.snapshot("status").unwrap().changed,
3645
        "out-of-scope files are not removals"
3646
    );
3647
    assert!(!a.quick_status().unwrap().dirty);
3648
3649
    // Edits in scope commit normally and keep the rest of the tree intact.
3650
    write(
3651
        &root.join("a"),
3652
        "src/lib.rs",
3653
        b"pub fn a() {}\npub fn b() {}\n",
3654
    );
3655
    let h2 = a.commit("edit lib", &[]).unwrap();
3656
    let st = a.load_state(&[h2]).unwrap().materialize();
3657
    assert!(
3658
        st.files.contains_key("docs/guide.md"),
3659
        "the state still has everything"
3660
    );
3661
    assert!(a.push("origin", false).unwrap()[0].ok);
3662
    origin.refresh().unwrap();
3663
    // Files created outside the scope are ignored by status.
3664
    write(&root.join("a"), "docs/new.md", b"ignored\n");
3665
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
3666
3667
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
3668
    let mut a = a;
3669
    a.config.set("filter.paths", "src,docs").unwrap();
3670
    a.save_config().unwrap();
3671
    let r = a
3672
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
3673
        .unwrap();
3674
    assert!(r.written >= 2);
3675
    assert_eq!(
3676
        fs::read(root.join("a/docs/logo.png")).unwrap(),
3677
        logo,
3678
        "now fetched lazily"
3679
    );
3680
    assert!(!root.join("a/README.md").exists());
3681
    // Origin sees the change made under a sparse checkout with the full tree intact.
3682
    origin.pull("origin").err();
3683
    let full = origin
3684
        .load_state(&origin.bookmark_heads().unwrap())
3685
        .unwrap()
3686
        .materialize();
3687
    assert!(
3688
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
3689
    );
3690
    assert!(full.files.contains_key("README.md"));
3691
    let _ = h1;
3692
}
3693
3694
/// #137: a depth-0 clone takes no change, so the blobs of the state's
3695
/// binary files came with nothing and the checkout failed ("object … not
3696
/// found"); they are fetched with the checkpoint, or left lazy under
3697
/// `--max-blob`.
3698
#[test]
3699
fn a_depth_0_clone_brings_its_binary_files() {
3700
    hermetic();
3701
    let dir = tempfile::tempdir().unwrap();
3702
    let root = dir.path();
3703
    let origin_dir = root.join("origin");
3704
    let origin = Repo::init(&origin_dir)
3705
        .unwrap()
3706
        .with_home(root.join("home"));
3707
    let png: Vec<u8> = (0..4000u32)
3708
        .map(|i| (i * 7 % 251) as u8)
3709
        .chain([0, 0xff])
3710
        .collect();
3711
    // The logo comes with a.txt's first line, and the head edits that line,
3712
    // so the change that set the logo is below the head, not a head itself.
3713
    write(&origin_dir, "logo.png", &png);
3714
    write(&origin_dir, "a.txt", b"first\n");
3715
    origin.commit("logo", &[]).unwrap();
3716
    write(&origin_dir, "a.txt", b"later\n");
3717
    origin.commit("later", &[]).unwrap();
3718
    assert_eq!(origin.bookmark_heads().unwrap().len(), 1);
3719
    let url = origin_dir.to_string_lossy().to_string();
3720
    Repo::clone_shallow(&url, &root.join("a"), 0, None, &[]).unwrap();
3721
    assert_eq!(fs::read(root.join("a/logo.png")).unwrap(), png);
3722
    let lazy = Repo::clone_shallow(&url, &root.join("b"), 0, Some(0), &[]).unwrap();
3723
    assert_eq!(fs::read(root.join("b/a.txt")).unwrap(), b"later\n");
3724
    let blob = {
3725
        let heads = lazy.bookmark_heads().unwrap();
3726
        let st = lazy.load_state_history(&heads).unwrap();
3727
        st.opaque_nodes()
3728
            .iter()
3729
            .flat_map(|n| st.live_blobs(n))
3730
            .next()
3731
            .unwrap()
3732
    };
3733
    assert_eq!(lazy.read_blob(&blob).unwrap(), png, "fetched on read");
3734
    // Depth 0 takes no change: the head is the boundary; the log comes from
3735
    // the checkpoint; a change on top commits and pushes.
3736
    let mut a = Repo::open(&root.join("a"))
3737
        .unwrap()
3738
        .with_home(root.join("home"));
3739
    let head = origin.bookmark_heads().unwrap()[0];
3740
    assert!(!a.store().has(&head), "no change fetched");
3741
    assert!(a.boundary().contains(&head));
3742
    assert_eq!(
3743
        a.log()
3744
            .unwrap()
3745
            .iter()
3746
            .filter(|e| !e.is_working_copy)
3747
            .count(),
3748
        2,
3749
        "the log from the checkpoint"
3750
    );
3751
    write(&root.join("a"), "a.txt", b"later\nmine\n");
3752
    a.config.set("remote.origin.url", &url).unwrap();
3753
    a.save_config().unwrap();
3754
    let mine = a.commit("mine", &[]).unwrap();
3755
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
3756
    origin.refresh().unwrap();
3757
    assert!(origin.store().has(&mine));
3758
    assert_eq!(origin.bookmark_heads().unwrap(), vec![mine]);
3759
    // And pulls what comes after.
3760
    origin
3761
        .checkout(&origin.bookmark_heads().unwrap(), false, "co")
3762
        .unwrap();
3763
    write(&origin_dir, "a.txt", b"later\nmine\ntheirs\n");
3764
    origin.snapshot("t").unwrap();
3765
    origin.commit("theirs", &[]).unwrap();
3766
    a.pull("origin").unwrap();
3767
    assert_eq!(
3768
        fs::read(root.join("a/a.txt")).unwrap(),
3769
        b"later\nmine\ntheirs\n"
3770
    );
3771
}
3772
3773
#[test]
3774
fn shallow_clone_and_deepen() {
3775
    hermetic();
3776
    let dir = tempfile::tempdir().unwrap();
3777
    let root = dir.path();
3778
    let origin_dir = root.join("origin");
3779
    let origin = Repo::init(&origin_dir)
3780
        .unwrap()
3781
        .with_home(root.join("home"));
3782
    let mut hashes = Vec::new();
3783
    for i in 0..8 {
3784
        write(
3785
            &origin_dir,
3786
            "a.txt",
3787
            format!(
3788
                "{}\n",
3789
                (0..=i)
3790
                    .map(|k| k.to_string())
3791
                    .collect::<Vec<_>>()
3792
                    .join("\n")
3793
            )
3794
            .as_bytes(),
3795
        );
3796
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
3797
    }
3798
    let url = origin_dir.to_string_lossy().to_string();
3799
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
3800
        .unwrap()
3801
        .with_home(root.join("home"));
3802
    assert!(a.is_shallow());
3803
    assert_eq!(
3804
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
3805
        "0\n1\n2\n3\n4\n5\n6\n7\n"
3806
    );
3807
    assert!(
3808
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
3809
        "three levels present"
3810
    );
3811
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
3812
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
3813
    assert_eq!(
3814
        a.log().unwrap().len(),
3815
        9,
3816
        "the log shows every change from the checkpoint's metadata"
3817
    );
3818
    assert!(!a.snapshot("status").unwrap().changed);
3819
    assert_eq!(a.quick_status().unwrap().heads, 1);
3820
3821
    // Work continues on top of the shallow history and pushes back.
3822
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
3823
    let h_new = a.commit("c8", &[]).unwrap();
3824
    assert!(a.push("origin", false).unwrap()[0].ok);
3825
    origin.refresh().unwrap();
3826
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
3827
    // Fetching new work from origin into the shallow clone works too.
3828
    write(&origin_dir, "b.txt", b"b\n");
3829
    origin.pull("origin").err();
3830
    let (_, wc) = origin.working_copy().unwrap();
3831
    let _ = wc;
3832
    origin
3833
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
3834
        .unwrap();
3835
    write(&origin_dir, "b.txt", b"b\n");
3836
    let h_b = origin.commit("b", &[]).unwrap();
3837
    let pr = a.pull("origin").unwrap();
3838
    assert!(pr.changed);
3839
    assert!(a.store().has(&h_b));
3840
    assert!(root.join("a/b.txt").exists());
3841
3842
    // Deepening fetches older history until the boundary is gone.
3843
    // Every commit also depends on the change that created the file, so two
3844
    // levels below the boundary hold h4, h3, and the root.
3845
    assert!(a.deepen("origin", 2).unwrap() >= 2);
3846
    assert!(a.store().has(&hashes[3]));
3847
    assert!(a.is_shallow());
3848
    a.deepen("origin", 100).unwrap();
3849
    assert!(!a.is_shallow(), "boundary reached the root");
3850
    assert!(a.store().has(&hashes[0]));
3851
    assert_eq!(
3852
        a.load_state_full(&a.bookmark_heads().unwrap())
3853
            .unwrap()
3854
            .len(),
3855
        10
3856
    );
3857
}
3858
3859
#[test]
3860
fn a_tag_is_withdrawn_by_a_signed_withdrawal() {
3861
    hermetic();
3862
    let dir = tempfile::tempdir().unwrap();
3863
    let root = dir.path();
3864
    let origin = Repo::init(&root.join("origin")).unwrap();
3865
    let url = root.join("origin").to_string_lossy().to_string();
3866
    let mut a = Repo::clone(&url, &root.join("a"))
3867
        .unwrap()
3868
        .with_home(root.join("home-a"));
3869
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
3870
        .unwrap();
3871
    write(&root.join("a"), "f.txt", b"1\n");
3872
    let h1 = a.commit("one", &[]).unwrap();
3873
    a.tag_create("v1", &[h1], "first release").unwrap();
3874
    a.tag_create("v2", &[h1], "").unwrap();
3875
    a.policy_init().unwrap();
3876
    a.push("origin", false).unwrap();
3877
    origin.refresh().unwrap();
3878
    let original = a
3879
        .tag_refs()
3880
        .unwrap()
3881
        .into_iter()
3882
        .find(|t| t.name == "v1")
3883
        .unwrap();
3884
    let b = Repo::clone(&url, &root.join("b"))
3885
        .unwrap()
3886
        .with_home(root.join("home-b"));
3887
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
3888
3889
    // A key the policy does not let create the tag may not withdraw it.
3890
    let mut c = Repo::clone(&url, &root.join("c"))
3891
        .unwrap()
3892
        .with_home(root.join("home-c"));
3893
    c.create_identity("Cy", "[email protected]", IdentityScope::User)
3894
        .unwrap();
3895
    let r = c.push_delete("origin", "tags/v1").unwrap();
3896
    assert!(
3897
        !r[0].ok && r[0].reason.contains("may not withdraw"),
3898
        "{r:?}"
3899
    );
3900
    assert_eq!(c.tag_heads("v1").unwrap(), None, "withdrawn there first");
3901
    origin.refresh().unwrap();
3902
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
3903
3904
    // Its creator's key may: the tag goes, the withdrawal stays.
3905
    let r = a.push_delete("origin", "tags/v1").unwrap();
3906
    assert!(r[0].ok && r[0].reason == "withdrawn", "{r:?}");
3907
    origin.refresh().unwrap();
3908
    assert_eq!(origin.tag_heads("v1").unwrap(), None);
3909
    assert_eq!(a.tag_heads("v1").unwrap(), None);
3910
    assert!(origin.tag_withdrawal("v1").unwrap().is_some());
3911
    assert!(origin.tag_attest("v1").unwrap().is_some(), "kept beside it");
3912
    let refs = origin.remote_refs().unwrap();
3913
    assert!(refs.tags.iter().all(|t| t.name != "v1"));
3914
    assert_eq!(refs.withdrawn.len(), 1);
3915
    let r = a.push_delete("origin", "tags/v1").unwrap();
3916
    assert!(r[0].ok && r[0].reason == "already withdrawn", "{r:?}");
3917
3918
    // A fetch withdraws it too, and the name is never used again.
3919
    let rep = b.fetch("origin").unwrap();
3920
    assert_eq!(rep.withdrawn_tags, vec!["v1".to_string()]);
3921
    assert_eq!(b.tag_heads("v1").unwrap(), None);
3922
    assert!(b.tag_create("v1", &[h1], "").is_err());
3923
    let r = origin
3924
        .receive_push(Bundle::default(), vec![], None, vec![original])
3925
        .unwrap();
3926
    assert!(!r[0].ok && r[0].reason.contains("withdrawn"), "{r:?}");
3927
3928
    // `oxy tag delete`, then a plain push, sends it.
3929
    a.tag_delete("v2", "tagged too early").unwrap();
3930
    let r = a.push("origin", false).unwrap();
3931
    assert!(
3932
        r.iter()
3933
            .any(|x| x.name == "tags/v2" && x.ok && x.reason == "withdrawn"),
3934
        "{r:?}"
3935
    );
3936
    origin.refresh().unwrap();
3937
    assert_eq!(origin.tag_heads("v2").unwrap(), None);
3938
    let (_, w) = origin.tag_withdrawal("v2").unwrap().unwrap();
3939
    assert!(
3940
        matches!(&w.attest.body, AttestBody::Untag { reason, .. } if reason == "tagged too early")
3941
    );
3942
}
3943
3944
#[test]
3945
fn tags_are_immutable_named_states_and_travel() {
3946
    hermetic();
3947
    let dir = tempfile::tempdir().unwrap();
3948
    let root = dir.path();
3949
    let origin = Repo::init(&root.join("origin")).unwrap();
3950
    let url = root.join("origin").to_string_lossy().to_string();
3951
    let mut a = Repo::clone(&url, &root.join("a"))
3952
        .unwrap()
3953
        .with_home(root.join("home-a"));
3954
    let (key_a, _) = a
3955
        .create_identity("Ada", "[email protected]", IdentityScope::User)
3956
        .unwrap();
3957
    write(&root.join("a"), "f.txt", b"1\n");
3958
    let h1 = a.commit("one", &[]).unwrap();
3959
    write(&root.join("a"), "f.txt", b"1\n2\n");
3960
    let h2 = a.commit("two", &[]).unwrap();
3961
3962
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
3963
    assert_eq!(
3964
        (t.heads.clone(), t.signer.as_deref()),
3965
        (vec![h1], Some("Ada"))
3966
    );
3967
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
3968
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
3969
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
3970
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
3971
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
3972
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
3973
    assert_eq!(sa.sigs[0].key, key_a);
3974
    // Without a policy every client is sent every tag, whatever features
3975
    // it declares (oxygen#131).
3976
    let mut refs = a.remote_refs().unwrap();
3977
    a.refs_for_client(&mut refs, None);
3978
    assert_eq!(refs.tags.len(), 1);
3979
    // Checkout by tag.
3980
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
3981
        .unwrap();
3982
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
3983
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
3984
        .unwrap();
3985
3986
    // Push carries the tag; a second attestation for the name is refused.
3987
    let r = a.push("origin", false).unwrap();
3988
    origin.refresh().unwrap();
3989
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
3990
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
3991
    let mut forged = a
3992
        .tag_refs()
3993
        .unwrap()
3994
        .into_iter()
3995
        .find(|t| t.name == "v1")
3996
        .unwrap();
3997
    forged.state = origin
3998
        .store()
3999
        .put_state(&StateObject::new(vec![h2]))
4000
        .unwrap();
4001
    forged.heads = vec![h2];
4002
    forged.attestation = None;
4003
    let r = origin
4004
        .receive_push(Bundle::default(), vec![], None, vec![forged])
4005
        .unwrap();
4006
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
4007
4008
    // A clone gets the tag; a later tag arrives on fetch.
4009
    let b = Repo::clone(&url, &root.join("b"))
4010
        .unwrap()
4011
        .with_home(root.join("home-b"));
4012
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
4013
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
4014
    a.tag_create("v2", &[h2], "second").unwrap();
4015
    a.push("origin", false).unwrap();
4016
    origin.refresh().unwrap();
4017
    let rep = b.fetch("origin").unwrap();
4018
    assert_eq!(rep.new_tags, 1);
4019
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
4020
4021
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
4022
    a.policy_init().unwrap();
4023
    a.push("origin", false).unwrap();
4024
    origin.refresh().unwrap();
4025
    let unattested = crate::protocol::TagRef::new(
4026
        "v3".into(),
4027
        origin
4028
            .store()
4029
            .put_state(&StateObject::new(vec![h2]))
4030
            .unwrap(),
4031
        vec![h2],
4032
        None,
4033
    );
4034
    let r = origin
4035
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
4036
        .unwrap();
4037
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
4038
    a.tag_create("v3", &[h2], "").unwrap();
4039
    let r = a.push("origin", false).unwrap();
4040
    origin.refresh().unwrap();
4041
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
4042
    assert!(a.gc(true).is_ok());
4043
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
4044
4045
    // After a rotation the policy names only the new key, yet a fresh clone
4046
    // still takes the tags the old key made before it; the old key makes
4047
    // nothing new.
4048
    let rot = a.rotate_identity().unwrap();
4049
    let r = a.push("origin", false).unwrap();
4050
    origin.refresh().unwrap();
4051
    assert!(r.iter().all(|x| x.ok), "{r:?}");
4052
    let c = Repo::clone(&url, &root.join("c"))
4053
        .unwrap()
4054
        .with_home(root.join("home-c"));
4055
    assert_eq!(c.tag_heads("v3").unwrap(), Some(vec![h2]));
4056
    let (_, sp) = c.current_policy().unwrap().unwrap();
4057
    assert!(!sp.policy.authorizes(&key_a, "tags/v9"));
4058
    let made = c.identity(&rot.new).unwrap().created;
4059
    assert!(c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made - 1));
4060
    assert!(!c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made));
4061
    assert!(!c.predecessor_authorized(&sp.policy, &rot.new, "tags/v9", 0));
4062
}
4063
4064
#[test]
4065
fn multiple_workspaces_share_a_repository() {
4066
    hermetic();
4067
    let dir = tempfile::tempdir().unwrap();
4068
    let root = dir.path();
4069
    let main_dir = root.join("main");
4070
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
4071
    write(&main_dir, "a.txt", b"a\n");
4072
    let h1 = repo.commit("a", &[]).unwrap();
4073
    assert_eq!(repo.workspaces().unwrap().len(), 1);
4074
4075
    // A second workspace elsewhere, checked out on the bookmark.
4076
    let ws_dir = root.join("ws2");
4077
    let ops = repo.op_log().unwrap().len();
4078
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
4079
    assert_eq!(
4080
        ws.op_log().unwrap().len(),
4081
        ops + 2,
4082
        "the add and its checkout, and no snapshot finding the tree deleted (oxygen#137)"
4083
    );
4084
    assert!(ws_dir.join(".oxy").is_file());
4085
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
4086
    assert_ne!(ws.workspace(), repo.workspace());
4087
    let list = repo.workspaces().unwrap();
4088
    assert_eq!(list.len(), 2);
4089
    assert!(list
4090
        .iter()
4091
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
4092
    assert!(!ws.snapshot("status").unwrap().changed);
4093
4094
    // Work in the second workspace: its own working copy, shared bookmark.
4095
    write(&ws_dir, "b.txt", b"b\n");
4096
    let s = ws.snapshot("status").unwrap();
4097
    assert_eq!(s.statuses.len(), 1);
4098
    assert!(
4099
        !repo.snapshot("status").unwrap().changed,
4100
        "the first workspace is untouched"
4101
    );
4102
    let h2 = ws.commit("b from ws2", &[]).unwrap();
4103
    repo.refresh().unwrap();
4104
    let mut heads = repo.bookmark_heads().unwrap();
4105
    heads.sort();
4106
    let mut want = vec![h1, h2];
4107
    want.sort();
4108
    assert_eq!(heads, want, "both workspaces see the bookmark move");
4109
    assert!(!main_dir.join("b.txt").exists());
4110
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
4111
        .unwrap();
4112
    assert!(main_dir.join("b.txt").exists());
4113
4114
    // Reopening from inside the second workspace finds the shared repository.
4115
    let reopened = Repo::open(&ws_dir).unwrap();
4116
    assert_eq!(reopened.workspace(), ws.workspace());
4117
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
4118
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
4119
4120
    // Workspaces cannot nest; forget drops one from the view but keeps files.
4121
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
4122
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
4123
    repo.workspace_forget(&ws.workspace()).unwrap();
4124
    assert_eq!(repo.workspaces().unwrap().len(), 1);
4125
    assert!(ws_dir.join("b.txt").exists());
4126
    assert!(
4127
        ws.snapshot("status").is_err(),
4128
        "a forgotten workspace is no longer in the view"
4129
    );
4130
4131
    // The working-copy lock: re-entrant in a thread; a lock whose process
4132
    // is gone is taken over, and a live process's is not, however old.
4133
    let lock = repo.lock_snapshot().unwrap();
4134
    let again = repo.lock_working_copy().unwrap();
4135
    drop(again);
4136
    drop(lock);
4137
    let lock_path = main_dir
4138
        .join(".oxy/workspaces")
4139
        .join(repo.workspace().to_hex())
4140
        .join("lock");
4141
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
4142
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
4143
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
4144
    age(&lock_path);
4145
    assert!(
4146
        !super::workspace::lock_is_stale(&lock_path),
4147
        "a live process keeps its lock"
4148
    );
4149
    fs::write(&lock_path, "4294967295").unwrap();
4150
    age(&lock_path);
4151
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
4152
}
4153
4154
#[test]
4155
fn attributes_binary_eol_nocompress_lockable() {
4156
    hermetic();
4157
    let dir = tempfile::tempdir().unwrap();
4158
    let root = dir.path();
4159
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4160
    write(
4161
        root,
4162
        ".oxyattributes",
4163
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
4164
    );
4165
    write(root, "plain.dat", b"no nul bytes here\n");
4166
    write(root, "notes.txt", b"one\r\ntwo\r\n");
4167
    write(root, "assets/model.bin", b"\0model");
4168
    let h = repo.commit("attrs", &[]).unwrap();
4169
    let snap = repo.load_state(&[h]).unwrap().materialize();
4170
    assert!(
4171
        snap.files["plain.dat"].mode.opaque,
4172
        "binary attribute forces opaque without NUL bytes"
4173
    );
4174
    assert!(
4175
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
4176
        "stored with LF"
4177
    );
4178
    assert!(
4179
        !repo.snapshot("status").unwrap().changed,
4180
        "CRLF on disk equals LF in the state"
4181
    );
4182
    // nocompress chunks pack raw.
4183
    let r = repo.gc(true).unwrap();
4184
    assert!(r.packed.objects > 0);
4185
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
4186
    fs::remove_file(root.join("notes.txt")).unwrap();
4187
    repo.checkout(&[h], true, "co").unwrap();
4188
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
4189
    assert!(fs::metadata(root.join("assets/model.bin"))
4190
        .unwrap()
4191
        .permissions()
4192
        .readonly());
4193
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
4194
    repo.lock_path("assets/model.bin").unwrap();
4195
    assert!(!fs::metadata(root.join("assets/model.bin"))
4196
        .unwrap()
4197
        .permissions()
4198
        .readonly());
4199
    assert!(repo.is_locked("assets/model.bin"));
4200
    write(root, "assets/model.bin", b"\0model2");
4201
    repo.commit("edit model", &[]).unwrap();
4202
    repo.unlock_path("assets/model.bin").unwrap();
4203
    assert!(fs::metadata(root.join("assets/model.bin"))
4204
        .unwrap()
4205
        .permissions()
4206
        .readonly());
4207
    // A later checkout can still overwrite a read-only lockable file.
4208
    repo.checkout(&[h], true, "co").unwrap();
4209
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
4210
}
4211
4212
#[cfg(unix)]
4213
#[test]
4214
fn hooks_can_veto_observe_and_add_dependencies() {
4215
    use std::os::unix::fs::PermissionsExt;
4216
    hermetic();
4217
    let dir = tempfile::tempdir().unwrap();
4218
    let root = dir.path();
4219
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
4220
    let hooks = root.join(".oxy/hooks");
4221
    fs::create_dir_all(&hooks).unwrap();
4222
    let hook = |name: &str, body: &str| {
4223
        let p = hooks.join(name);
4224
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
4225
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
4226
    };
4227
    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");
4228
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
4229
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
4230
    hook("pre-push", "echo pushing blocked >&2; exit 3");
4231
    write(root, ".oxyignore", b".last-*\n");
4232
    write(root, "a.txt", b"a\n");
4233
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
4234
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
4235
    let h1 = repo.commit("first", &[]).unwrap();
4236
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
4237
    assert!(
4238
        pre.contains("\"event\":\"pre-commit\"")
4239
            && pre.contains("\"path\":\"a.txt\"")
4240
            && pre.contains("\"message\":\"first\""),
4241
        "{pre}"
4242
    );
4243
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
4244
    assert!(post.contains(&h1.to_hex()), "{post}");
4245
    repo.checkout(&[h1], false, "co").unwrap();
4246
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
4247
        .unwrap()
4248
        .contains("post-checkout"));
4249
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
4250
    repo.save_config().unwrap();
4251
    let err = repo.push("origin", false).unwrap_err().to_string();
4252
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
4253
4254
    // semantic-deps: only when enabled; adds an explicit dependency.
4255
    write(root, "b.txt", b"b\n");
4256
    hook(
4257
        "semantic-deps",
4258
        &format!(
4259
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
4260
            h1.to_hex()
4261
        ),
4262
    );
4263
    let h2 = repo.commit("b without hook", &[]).unwrap();
4264
    assert!(
4265
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
4266
        "hook disabled by default"
4267
    );
4268
    repo.config.set("hooks.semantic-deps", "true").unwrap();
4269
    repo.save_config().unwrap();
4270
    write(root, "c.txt", b"c\n");
4271
    let h3 = repo.commit("c with hook", &[]).unwrap();
4272
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
4273
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
4274
    assert!(
4275
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
4276
        "{sem}"
4277
    );
4278
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
4279
}
4280
4281
#[test]
4282
fn amend_into_older_change_and_split() {
4283
    hermetic();
4284
    let dir = tempfile::tempdir().unwrap();
4285
    let root = dir.path();
4286
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
4287
    repo.create_identity("Ada", "a@b", IdentityScope::User)
4288
        .unwrap();
4289
    repo.set_user_config("core.sign", "change").unwrap();
4290
    write(root, "a.txt", b"one\ntwo\n");
4291
    let h0 = repo.commit("base", &[]).unwrap();
4292
    write(root, "a.txt", b"one\nTWO\n");
4293
    let h1 = repo.commit("edit two", &[]).unwrap();
4294
    write(root, "a.txt", b"one\nTWO\nthree\n");
4295
    let h2 = repo.commit("add three", &[]).unwrap();
4296
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
4297
4298
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
4299
    write(root, "a.txt", b"one\nTWO!\nthree\n");
4300
    let h1b = repo.amend_into(&h1, None).unwrap();
4301
    assert_ne!(h1b, h1);
4302
    let c1b = repo.store().get_change(&h1b).unwrap();
4303
    assert_eq!(c1b.change_id, id1);
4304
    assert_eq!(c1b.deps, vec![h0]);
4305
    assert!(matches!(
4306
        repo.verify_change(&h1b).unwrap(),
4307
        SignatureStatus::Valid { .. }
4308
    ));
4309
    let heads = repo.bookmark_heads().unwrap();
4310
    assert_eq!(heads.len(), 1);
4311
    let top = repo.store().get_change(&heads[0]).unwrap();
4312
    assert_eq!(top.message, "add three");
4313
    assert_eq!(
4314
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
4315
        [h0, h1b].into_iter().collect(),
4316
        "depends on the file's creator and the rewritten line"
4317
    );
4318
    let snap = repo.load_state(&heads).unwrap().materialize();
4319
    assert!(
4320
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
4321
    );
4322
    assert!(
4323
        !repo.snapshot("status").unwrap().changed,
4324
        "the working copy is clean after folding"
4325
    );
4326
    // Only h1b's own state shows the fix without "three".
4327
    let only = repo.load_state(&[h1b]).unwrap().materialize();
4328
    assert!(
4329
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
4330
    );
4331
    assert_eq!(repo.log().unwrap().len(), 4);
4332
4333
    // An edit to a line introduced by h2 cannot fold into h1.
4334
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
4335
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
4336
    assert!(err.contains("introduced after"), "{err}");
4337
    assert!(
4338
        repo.snapshot("status").unwrap().statuses.len() == 1,
4339
        "nothing was changed by the refusal"
4340
    );
4341
    write(root, "a.txt", b"one\nTWO!\nthree\n");
4342
4343
    // Split the head that touches two files.
4344
    write(root, "b.txt", b"b\n");
4345
    write(root, "c.txt", b"c\n");
4346
    let h3 = repo.commit("b and c", &[]).unwrap();
4347
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
4348
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
4349
    let c_1 = repo.store().get_change(&p1).unwrap();
4350
    let c_2 = repo.store().get_change(&p2).unwrap();
4351
    assert!(c_1.message.contains("part 1: b.txt"));
4352
    assert_eq!(c_2.change_id, id3);
4353
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
4354
    assert!(
4355
        heads.contains(&p1) && heads.contains(&p2),
4356
        "independent parts are both heads"
4357
    );
4358
    let snap = repo
4359
        .load_state(&repo.bookmark_heads().unwrap())
4360
        .unwrap()
4361
        .materialize();
4362
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
4363
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
4364
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
4365
    assert!(!repo.snapshot("status").unwrap().changed);
4366
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
4367
    let _ = h2;
4368
}
4369
4370
#[test]
4371
fn identity_lifecycle() {
4372
    hermetic();
4373
    let dir = tempfile::tempdir().unwrap();
4374
    let root = dir.path();
4375
    let origin = Repo::init(&root.join("origin")).unwrap();
4376
    let url = root.join("origin").to_string_lossy().to_string();
4377
    let mut a = Repo::clone(&url, &root.join("a"))
4378
        .unwrap()
4379
        .with_home(root.join("home-a"));
4380
    a.set_user_config("core.sign", "change").unwrap();
4381
    let (key_a, _) = a
4382
        .create_identity("Ada", "[email protected]", IdentityScope::User)
4383
        .unwrap();
4384
    write(&root.join("a"), "a.txt", b"a\n");
4385
    let h1 = a.commit("one", &[]).unwrap();
4386
    assert!(a.policy_init().unwrap().applied);
4387
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
4388
    origin.refresh().unwrap();
4389
4390
    // Expiry: an identity that had expired when the change was made does not authenticate it.
4391
    let mut e = Repo::init(&root.join("e"))
4392
        .unwrap()
4393
        .with_home(root.join("home-e"));
4394
    e.set_user_config("core.sign", "change").unwrap();
4395
    e.create_identity_with(
4396
        "Eve",
4397
        "[email protected]",
4398
        IdentityScope::User,
4399
        Some(Hlc::now().wall_ms - 1),
4400
    )
4401
    .unwrap();
4402
    write(&root.join("e"), "e.txt", b"e\n");
4403
    let he = e.commit("late", &[]).unwrap();
4404
    assert!(
4405
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
4406
    );
4407
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
4408
    let r = e
4409
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
4410
        .unwrap();
4411
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
4412
    write(&root.join("e"), "e.txt", b"e2\n");
4413
    let he2 = e.commit("in time", &[]).unwrap();
4414
    assert!(
4415
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
4416
    );
4417
4418
    // Rotation: a fresh key; the old change still verifies; the policy follows.
4419
    let r = a.rotate_identity().unwrap();
4420
    assert_eq!(r.old, key_a);
4421
    assert_eq!(a.config.author_key, Some(r.new));
4422
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
4423
    assert!(r.policy.as_ref().unwrap().applied);
4424
    let (_, sp) = a.current_policy().unwrap().unwrap();
4425
    assert_eq!(
4426
        (sp.policy.serial, sp.policy.roots.clone()),
4427
        (2, vec![r.new])
4428
    );
4429
    assert!(
4430
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
4431
        "superseded, not revoked"
4432
    );
4433
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
4434
    assert!(
4435
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
4436
    );
4437
    write(&root.join("a"), "a.txt", b"a2\n");
4438
    let h2 = a.commit("two", &[]).unwrap();
4439
    assert!(
4440
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
4441
    );
4442
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
4443
    let res = a.push("origin", false).unwrap();
4444
    origin.refresh().unwrap();
4445
    assert!(res.iter().all(|x| x.ok), "{res:?}");
4446
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
4447
    let key_a = r.new;
4448
4449
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
4450
    // identity object, so Ada's KeyId changes while her keys stay the same.
4451
    let mut b = Repo::clone(&url, &root.join("b"))
4452
        .unwrap()
4453
        .with_home(root.join("home-b"));
4454
    let (key_b, id_b) = b
4455
        .create_identity("Bob", "[email protected]", IdentityScope::User)
4456
        .unwrap();
4457
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
4458
    assert_eq!(r.old, key_a);
4459
    let key_a2 = r.new;
4460
    assert_eq!(
4461
        a.identity(&key_a2).unwrap().delegates,
4462
        vec![Delegate::full(key_b)]
4463
    );
4464
    assert_eq!(
4465
        a.identity(&key_a2).unwrap().ed25519_pk,
4466
        a.identity(&key_a).unwrap().ed25519_pk
4467
    );
4468
    assert!(
4469
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
4470
        "already a delegate"
4471
    );
4472
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
4473
    origin.refresh().unwrap();
4474
    write(&root.join("a"), "a.txt", b"a3\n");
4475
    let h3 = a.commit("three", &[]).unwrap();
4476
    assert!(
4477
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
4478
        "the same secret signs under the new KeyId"
4479
    );
4480
    // A change authored by Ada but signed only by Bob verifies through the delegation.
4481
    a.set_user_config("core.sign", "seal").unwrap();
4482
    write(&root.join("a"), "a.txt", b"a4\n");
4483
    let h4 = a.commit("four", &[]).unwrap();
4484
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
4485
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
4486
    a.store()
4487
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
4488
        .unwrap();
4489
    assert!(
4490
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
4491
    );
4492
    a.set_user_config("core.sign", "change").unwrap();
4493
    // Withdrawing the delegation re-issues the identity again.
4494
    let r = a.delegate_remove(&key_b).unwrap();
4495
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
4496
    assert!(a.delegate_remove(&key_b).is_err());
4497
    let key_a3 = r.new;
4498
    let res = a.push("origin", false).unwrap();
4499
    origin.refresh().unwrap();
4500
    assert!(res.iter().all(|x| x.ok), "{res:?}");
4501
4502
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
4503
    // both applied under the old threshold of 1. A grant then needs Bob too.
4504
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
4505
    assert!(a.policy_root_add(id_b.clone()).is_err());
4506
    assert!(a.policy_set_threshold(3).is_err());
4507
    assert!(a.policy_set_threshold(2).unwrap().applied);
4508
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
4509
    origin.refresh().unwrap();
4510
    b.pull("origin").unwrap();
4511
    assert_eq!(
4512
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
4513
        2
4514
    );
4515
    let mut c = Repo::init(&root.join("c"))
4516
        .unwrap()
4517
        .with_home(root.join("home-c"));
4518
    let (key_c, id_c) = c
4519
        .create_identity("Cy", "[email protected]", IdentityScope::User)
4520
        .unwrap();
4521
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
4522
    let proposal = a.policy_grant(id_c, None).unwrap();
4523
    assert!(!proposal.applied && proposal.sigs.len() == 1);
4524
    assert_eq!(proposal.policy.serial, serial_before + 1);
4525
    assert_eq!(
4526
        a.current_policy().unwrap().unwrap().1.policy.serial,
4527
        serial_before,
4528
        "a proposal changes nothing yet"
4529
    );
4530
    // Bob signs the proposal, handed over as a file, and it applies for him.
4531
    let bytes = proposal.signed().encode();
4532
    let signed = b
4533
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
4534
        .unwrap();
4535
    assert!(signed.applied && signed.sigs.len() == 2);
4536
    assert!(b
4537
        .current_policy()
4538
        .unwrap()
4539
        .unwrap()
4540
        .1
4541
        .policy
4542
        .authorizes(&key_c, "main"));
4543
    assert!(
4544
        b.policy_sign(signed.signed()).is_err(),
4545
        "a stale proposal is refused"
4546
    );
4547
    // Bob publishes it and Ada picks it up.
4548
    assert!(b
4549
        .push("origin", false)
4550
        .unwrap()
4551
        .iter()
4552
        .any(|x| x.name == "policy" && x.ok));
4553
    origin.refresh().unwrap();
4554
    a.pull("origin").unwrap();
4555
    assert_eq!(
4556
        a.current_policy().unwrap().unwrap().1.policy.serial,
4557
        serial_before + 1
4558
    );
4559
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
4560
    assert!(a.policy_revoke(&key_a3).is_err());
4561
    let u = a
4562
        .revoke_identity(&key_c, "left the project")
4563
        .unwrap()
4564
        .unwrap();
4565
    assert!(!u.applied);
4566
    assert!(a.is_revoked(&key_c).unwrap());
4567
    assert!(!b.is_revoked(&key_c).unwrap());
4568
    let u = b.policy_sign(u.signed()).unwrap();
4569
    assert!(u.applied && u.policy.is_revoked(&key_c));
4570
    assert!(b.is_revoked(&key_c).unwrap());
4571
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
4572
    assert!(
4573
        b.policy_revoke(&key_a3).is_err(),
4574
        "would leave one root for a threshold of 2"
4575
    );
4576
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
4577
    let key_c_own = c.config.author_key.unwrap();
4578
    assert!(c
4579
        .revoke_identity(&key_c_own, "lost laptop")
4580
        .unwrap()
4581
        .is_none());
4582
    assert!(c.is_revoked(&key_c_own).unwrap());
4583
    assert_eq!(key_c_own, key_c);
4584
}
4585
4586
#[test]
4587
fn renames_are_detected_and_tracked_as_moves() {
4588
    hermetic();
4589
    let dir = tempfile::tempdir().unwrap();
4590
    let root = dir.path();
4591
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4592
    write(
4593
        root,
4594
        "src/old.rs",
4595
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
4596
    );
4597
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
4598
    write(root, "tiny.txt", b"x\n");
4599
    let h1 = repo.commit("base", &[]).unwrap();
4600
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
4601
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
4602
4603
    // Rename with a small edit, a binary moved unchanged, and a rewrite
4604
    // that shares nothing with the removed file.
4605
    fs::remove_file(root.join("src/old.rs")).unwrap();
4606
    write(
4607
        root,
4608
        "lib/new.rs",
4609
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
4610
    );
4611
    fs::remove_file(root.join("img.bin")).unwrap();
4612
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
4613
    fs::remove_file(root.join("tiny.txt")).unwrap();
4614
    write(root, "other.txt", b"completely different\n");
4615
    let snap = repo.snapshot("status").unwrap();
4616
    let statuses: Vec<(&str, ChangeStatus)> = snap
4617
        .statuses
4618
        .iter()
4619
        .map(|s| (s.path.as_str(), s.status))
4620
        .collect();
4621
    assert_eq!(
4622
        statuses,
4623
        vec![
4624
            ("assets/img.bin", ChangeStatus::Renamed),
4625
            ("lib/new.rs", ChangeStatus::Renamed),
4626
            ("other.txt", ChangeStatus::Added),
4627
            ("src", ChangeStatus::Removed),
4628
            ("tiny.txt", ChangeStatus::Removed)
4629
        ]
4630
    );
4631
    let h2 = repo.commit("move things", &[]).unwrap();
4632
    let c = repo.store().get_change(&h2).unwrap();
4633
    let moves: Vec<_> = c
4634
        .tree_ops
4635
        .iter()
4636
        .filter(|op| matches!(op, TreeOp::Move { .. }))
4637
        .collect();
4638
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
4639
    assert!(c.tree_ops.iter().any(
4640
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
4641
    ));
4642
    assert!(c.tree_ops.iter().any(
4643
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
4644
    ));
4645
    let snap = repo.load_state(&[h2]).unwrap().materialize();
4646
    assert_eq!(
4647
        snap.files["lib/new.rs"].node, node_old,
4648
        "the node survives the rename"
4649
    );
4650
    assert!(
4651
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
4652
    );
4653
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
4654
    assert!(render_change(
4655
        &c,
4656
        &repo.load_state(&[h1]).unwrap(),
4657
        &repo.load_state(&[h1]).unwrap().materialize()
4658
    )
4659
    .contains("R src/old.rs -> lib/new.rs"));
4660
    // A fresh checkout reproduces the tree.
4661
    let other = tempfile::tempdir().unwrap();
4662
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
4663
    assert_eq!(
4664
        fs::read(other.path().join("lib/new.rs")).unwrap(),
4665
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
4666
    );
4667
    assert!(!other.path().join("src").exists());
4668
    assert!(!clone.snapshot("status").unwrap().changed);
4669
    // Similarity is line based, byte weighted.
4670
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
4671
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
4672
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
4673
    assert_eq!(similarity(b"", b"x\n"), 0);
4674
}
4675
4676
#[test]
4677
fn git_fetch_and_push_round_trip() {
4678
    hermetic();
4679
    if std::process::Command::new("git")
4680
        .arg("--version")
4681
        .output()
4682
        .is_err()
4683
    {
4684
        eprintln!("git not installed; skipping");
4685
        return;
4686
    }
4687
    let dir = tempfile::tempdir().unwrap();
4688
    let root = dir.path();
4689
    let git_in = |d: &Path, args: &[&str]| -> String {
4690
        let out = std::process::Command::new("git")
4691
            .arg("-C")
4692
            .arg(d)
4693
            .args([
4694
                "-c",
4695
                "user.name=Grace",
4696
                "-c",
4697
                "[email protected]",
4698
                "-c",
4699
                "commit.gpgsign=false",
4700
            ])
4701
            .args(args)
4702
            .output()
4703
            .unwrap();
4704
        assert!(
4705
            out.status.success(),
4706
            "git {args:?}: {}",
4707
            String::from_utf8_lossy(&out.stderr)
4708
        );
4709
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4710
    };
4711
    // A bare "remote" and a work tree that pushes to it.
4712
    let remote = root.join("remote.git");
4713
    fs::create_dir_all(&remote).unwrap();
4714
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
4715
    let work = root.join("work");
4716
    git_in(
4717
        root,
4718
        &[
4719
            "clone",
4720
            "-q",
4721
            remote.to_str().unwrap(),
4722
            work.to_str().unwrap(),
4723
        ],
4724
    );
4725
    git_in(&work, &["checkout", "-q", "-b", "main"]);
4726
    write(&work, "README.md", b"# Project\n");
4727
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
4728
    git_in(&work, &["add", "."]);
4729
    git_in(&work, &["commit", "-q", "-m", "initial"]);
4730
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
4731
    git_in(&work, &["commit", "-q", "-am", "second"]);
4732
    git_in(&work, &["push", "-q", "origin", "main"]);
4733
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
4734
4735
    // Fetch into a fresh oxy repository.
4736
    let o = root.join("oxy");
4737
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
4738
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
4739
        .unwrap();
4740
    let url = remote.to_string_lossy().to_string();
4741
    let r = repo.git_fetch(&url, "main").unwrap();
4742
    assert_eq!((r.commits, r.heads), (2, 1));
4743
    assert_eq!(
4744
        fs::read(o.join("src/lib.rs")).unwrap(),
4745
        b"pub fn a() {}\npub fn b() {}\n"
4746
    );
4747
    assert!(!repo.snapshot("status").unwrap().changed);
4748
    assert_eq!(
4749
        repo.git_fetch(&url, "main").unwrap().commits,
4750
        0,
4751
        "nothing new"
4752
    );
4753
4754
    // An oxy change, pushed back: one commit on top of the Git tip.
4755
    write(
4756
        &o,
4757
        "src/lib.rs",
4758
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
4759
    );
4760
    write(&o, "NOTES.md", b"from oxy\n");
4761
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
4762
    let r = repo.git_push(&url, "main").unwrap();
4763
    assert_eq!(r.exported, 1, "{r:?}");
4764
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
4765
    assert_eq!(
4766
        git_in(&work, &["log", "--format=%s", "main"]),
4767
        "add c and notes\nsecond\ninitial"
4768
    );
4769
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
4770
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
4771
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
4772
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
4773
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
4774
    assert_eq!(
4775
        repo.git_push(&url, "main").unwrap().exported,
4776
        0,
4777
        "already pushed"
4778
    );
4779
4780
    // Git moves on; pushing without fetching is refused, fetching brings
4781
    // the commit in and the working copy follows.
4782
    write(&work, "README.md", b"# Project\n\nMore.\n");
4783
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
4784
    git_in(&work, &["push", "-q", "origin", "main"]);
4785
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
4786
    assert!(repo
4787
        .git_push(&url, "main")
4788
        .unwrap_err()
4789
        .to_string()
4790
        .contains("fetch"));
4791
    let r = repo.git_fetch(&url, "main").unwrap();
4792
    assert_eq!(
4793
        (r.commits, r.heads),
4794
        (1, 2),
4795
        "the Git change and the oxy change commute"
4796
    );
4797
    assert_eq!(
4798
        fs::read(o.join("README.md")).unwrap(),
4799
        b"# Project\n\nMore.\n"
4800
    );
4801
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
4802
    assert!(!repo.snapshot("status").unwrap().changed);
4803
    // Another oxy change pushes on top of Git's newest commit.
4804
    write(&o, "NOTES.md", b"from oxy\nagain\n");
4805
    repo.commit("notes again", &[]).unwrap();
4806
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
4807
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
4808
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
4809
    assert_eq!(
4810
        fs::read(work.join("NOTES.md")).unwrap(),
4811
        b"from oxy\nagain\n"
4812
    );
4813
    assert_eq!(
4814
        git_in(&work, &["log", "--format=%s", "main"])
4815
            .lines()
4816
            .count(),
4817
        5
4818
    );
4819
}
4820
4821
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
4822
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
4823
#[test]
4824
#[ignore]
4825
fn bench_one_gibibyte_file() {
4826
    hermetic();
4827
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
4828
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
4829
        Some(d) => tempfile::tempdir_in(d).unwrap(),
4830
        None => tempfile::tempdir().unwrap(),
4831
    };
4832
    let root = dir.path();
4833
    let repo = Repo::init(&root.join("r"))
4834
        .unwrap()
4835
        .with_home(root.join("home"));
4836
    let size = 1usize << 30;
4837
    let mut data = vec![0u8; size];
4838
    let mut x = 0x9e3779b97f4a7c15u64;
4839
    for chunk in data.chunks_mut(8) {
4840
        x ^= x << 13;
4841
        x ^= x >> 7;
4842
        x ^= x << 17;
4843
        let b = x.to_le_bytes();
4844
        chunk.copy_from_slice(&b[..chunk.len()]);
4845
    }
4846
    let t = std::time::Instant::now();
4847
    write(&root.join("r"), "big.bin", &data);
4848
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
4849
    let t = std::time::Instant::now();
4850
    let h = repo.commit("big", &[]).unwrap();
4851
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
4852
    let t = std::time::Instant::now();
4853
    assert!(!repo.snapshot("status").unwrap().changed);
4854
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
4855
    let t = std::time::Instant::now();
4856
    let objects = repo.store().list().unwrap().len();
4857
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
4858
    let t = std::time::Instant::now();
4859
    let g = repo.gc(true).unwrap();
4860
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
4861
    let t = std::time::Instant::now();
4862
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
4863
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
4864
    let t = std::time::Instant::now();
4865
    let back = fs::read(root.join("c/big.bin")).unwrap();
4866
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
4867
    eprintln!("read back and verify: {:.2?}", t.elapsed());
4868
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
4869
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
4870
    eprintln!(
4871
        "store size: {:.1} MiB for 1 GiB of data",
4872
        store_bytes as f64 / (1024.0 * 1024.0)
4873
    );
4874
}
4875
4876
fn walkdir_size(p: &Path) -> u64 {
4877
    let mut total = 0;
4878
    if let Ok(rd) = fs::read_dir(p) {
4879
        for e in rd.flatten() {
4880
            let path = e.path();
4881
            if path.is_dir() {
4882
                total += walkdir_size(&path);
4883
            } else if let Ok(m) = fs::metadata(&path) {
4884
                total += m.len();
4885
            }
4886
        }
4887
    }
4888
    total
4889
}
4890
4891
/// An opaque file whose size and mtime match the manifest is not read on
4892
/// the next snapshot: its blob comes from the manifest's stat cache.
4893
#[cfg(unix)]
4894
#[test]
4895
fn stat_cache_skips_reading_unchanged_opaque_files() {
4896
    use std::os::unix::fs::PermissionsExt;
4897
    hermetic();
4898
    let dir = tempfile::tempdir().unwrap();
4899
    let root = dir.path();
4900
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4901
    let mut big = vec![0u8; 300 * 1024];
4902
    for (i, b) in big.iter_mut().enumerate() {
4903
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
4904
    }
4905
    big[0] = 0;
4906
    write(root, "big.bin", &big);
4907
    write(root, "a.txt", b"text\n");
4908
    let h1 = repo.commit("base", &[]).unwrap();
4909
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4910
    assert!(
4911
        m.entries["big.bin"].blob.is_some(),
4912
        "opaque files record their blob"
4913
    );
4914
    assert!(m.entries["a.txt"].blob.is_none());
4915
    let blob = m.entries["big.bin"].blob.unwrap();
4916
    assert!(repo.store().has(&blob));
4917
4918
    // Files modified within two seconds of the manifest are racy and still
4919
    // read; age the file so the cache applies, then snapshot to record it.
4920
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4921
    fs::File::options()
4922
        .write(true)
4923
        .open(root.join("big.bin"))
4924
        .unwrap()
4925
        .set_modified(old)
4926
        .unwrap();
4927
    assert!(!repo.snapshot("status").unwrap().changed);
4928
    // Now the file cannot be read at all; the snapshot succeeds without it.
4929
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
4930
    let snap = repo.snapshot("status").unwrap();
4931
    assert!(
4932
        !snap.changed && snap.statuses.is_empty(),
4933
        "{:?}",
4934
        snap.statuses
4935
    );
4936
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
4937
    // A real change (new mtime, new content) is seen and committed correctly.
4938
    let mut big2 = big.clone();
4939
    big2[10] ^= 0xff;
4940
    write(root, "big.bin", &big2);
4941
    let snap = repo.snapshot("status").unwrap();
4942
    assert_eq!(
4943
        snap.statuses
4944
            .iter()
4945
            .map(|s| (s.path.as_str(), s.status))
4946
            .collect::<Vec<_>>(),
4947
        vec![("big.bin", ChangeStatus::Modified)]
4948
    );
4949
    let h2 = repo.commit("edit", &[]).unwrap();
4950
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
4951
    assert_eq!(
4952
        files["big.bin"].content,
4953
        FileContent::Opaque {
4954
            blobs: vec![Repo::blob_ref(&big2)]
4955
        }
4956
    );
4957
    // Checkout writes a manifest with blobs too, so the next status is cached.
4958
    repo.checkout(&[h1], false, "checkout").unwrap();
4959
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4960
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
4961
    assert!(!repo.snapshot("status").unwrap().changed);
4962
}
4963
4964
#[test]
4965
fn status_json_lists_conflicts_with_contributors() {
4966
    hermetic();
4967
    let dir = tempfile::tempdir().unwrap();
4968
    let root = dir.path();
4969
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4970
    write(root, "a.txt", b"one\n");
4971
    let h1 = repo.commit("base", &[]).unwrap();
4972
    write(root, "a.txt", b"one\nleft\n");
4973
    let ha = repo.commit("left", &[]).unwrap();
4974
    repo.checkout(&[h1], true, "checkout").unwrap();
4975
    write(root, "a.txt", b"one\nright\n");
4976
    let hb = repo.commit("right", &[]).unwrap();
4977
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
4978
    let snap = repo.snapshot("status").unwrap();
4979
    assert!(snap.base_snapshot.is_conflicted());
4980
    let json = repo.status_json(&snap).unwrap();
4981
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
4982
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
4983
    assert!(json.contains("\"conflicted\":true"), "{json}");
4984
    assert!(
4985
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
4986
        "{json}"
4987
    );
4988
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
4989
    assert!(json.contains("\"resolved\":false"), "{json}");
4990
    assert!(json.starts_with('{') && json.ends_with('}'));
4991
    // Resolve and the report says so; a clean copy has no conflicts.
4992
    write(root, "a.txt", b"one\nleft\nright\n");
4993
    let snap = repo.snapshot("status").unwrap();
4994
    let json = repo.status_json(&snap).unwrap();
4995
    assert!(json.contains("\"resolved\":true"), "{json}");
4996
    repo.commit("resolve", &[]).unwrap();
4997
    let snap = repo.snapshot("status").unwrap();
4998
    let json = repo.status_json(&snap).unwrap();
4999
    assert!(
5000
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
5001
        "{json}"
5002
    );
5003
}
5004
5005
#[test]
5006
fn ignore_rules_do_not_untrack_files() {
5007
    hermetic();
5008
    let dir = tempfile::tempdir().unwrap();
5009
    let root = dir.path();
5010
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5011
    write(root, "src.c", b"int x;\n");
5012
    write(root, "build/out.o", b"\0obj");
5013
    write(root, "sub/keep.log", b"keep\n");
5014
    write(root, "sub/junk.log", b"junk\n");
5015
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
5016
    let snap = repo.snapshot("status").unwrap();
5017
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
5018
    assert_eq!(
5019
        added,
5020
        vec![".oxyignore", "src.c", "sub/keep.log"],
5021
        "anchored, glob, and negated rules"
5022
    );
5023
    let h1 = repo.commit("base", &[]).unwrap();
5024
    // Ignoring a tracked file changes nothing about it.
5025
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
5026
    let snap = repo.snapshot("status").unwrap();
5027
    assert_eq!(
5028
        snap.statuses
5029
            .iter()
5030
            .map(|s| s.path.as_str())
5031
            .collect::<Vec<_>>(),
5032
        vec![".oxyignore"]
5033
    );
5034
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
5035
    assert!(repo
5036
        .load_state(&[h2])
5037
        .unwrap()
5038
        .materialize()
5039
        .files
5040
        .contains_key("src.c"));
5041
    // Its edits are still seen, by status and by the prompt.
5042
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
5043
    write(root, "src.c", b"int x, y;\n");
5044
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
5045
    let snap = repo.snapshot("status").unwrap();
5046
    assert_eq!(
5047
        snap.statuses
5048
            .iter()
5049
            .map(|s| (s.path.as_str(), s.status))
5050
            .collect::<Vec<_>>(),
5051
        vec![("src.c", ChangeStatus::Modified)]
5052
    );
5053
    let h3 = repo.commit("edit src.c", &[]).unwrap();
5054
    assert!(
5055
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
5056
    );
5057
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
5058
    fs::remove_file(root.join("src.c")).unwrap();
5059
    let snap = repo.snapshot("status").unwrap();
5060
    assert_eq!(
5061
        snap.statuses
5062
            .iter()
5063
            .map(|s| (s.path.as_str(), s.status))
5064
            .collect::<Vec<_>>(),
5065
        vec![("src.c", ChangeStatus::Removed)]
5066
    );
5067
    repo.checkout(&[h3], true, "checkout").unwrap();
5068
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
5069
    assert!(!repo.snapshot("status").unwrap().changed);
5070
    let _ = h1;
5071
}
5072
5073
#[test]
5074
fn split_works_on_non_heads_by_node() {
5075
    hermetic();
5076
    let dir = tempfile::tempdir().unwrap();
5077
    let root = dir.path();
5078
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5079
    write(root, "a.txt", b"one\n");
5080
    write(root, "junk/x.lock", b"lock\n");
5081
    let h1 = repo.commit("work plus junk", &[]).unwrap();
5082
    write(root, "a.txt", b"one\ntwo\n");
5083
    let h2 = repo.commit("more work", &[]).unwrap();
5084
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
5085
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
5086
    // h1 is not a head: split it by node.
5087
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
5088
    assert_ne!(h1b, h1);
5089
    assert_eq!(
5090
        repo.store().get_change(&h1b).unwrap().change_id,
5091
        id1,
5092
        "the rest keeps the ChangeId"
5093
    );
5094
    let junk = repo.store().get_change(&hj).unwrap();
5095
    assert!(junk.tree_ops.iter().all(
5096
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
5097
    ));
5098
    let heads = repo.bookmark_heads().unwrap();
5099
    assert!(
5100
        heads.contains(&hj),
5101
        "the split-off part is a head of its own"
5102
    );
5103
    let snap = repo.load_state(&heads).unwrap().materialize();
5104
    assert!(
5105
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
5106
        "the dependent was rewritten onto the new hash"
5107
    );
5108
    assert!(snap.files.contains_key("junk/x.lock"));
5109
    let h2b = heads
5110
        .iter()
5111
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
5112
        .copied()
5113
        .unwrap();
5114
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
5115
    assert!(!repo.snapshot("status").unwrap().changed);
5116
    // Abandoning the split-off head removes the junk from history.
5117
    repo.abandon(&hj).unwrap();
5118
    let heads = repo.bookmark_heads().unwrap();
5119
    let snap = repo.load_state(&heads).unwrap().materialize();
5120
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
5121
    assert!(snap.files.contains_key("a.txt"));
5122
    // A dependent that touches the split-off paths blocks the split.
5123
    write(root, "junk/y.lock", b"y\n");
5124
    let hb = repo.commit("junk base", &[]).unwrap();
5125
    write(root, "junk/y.lock", b"yy\n");
5126
    write(root, "b.txt", b"b\n");
5127
    repo.commit("touches junk", &[]).unwrap();
5128
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
5129
    assert!(err.contains("depends on the split-off paths"), "{err}");
5130
}
5131
5132
#[test]
5133
fn bookmarks_switch_merge_and_push() {
5134
    hermetic();
5135
    let dir = tempfile::tempdir().unwrap();
5136
    let root = dir.path();
5137
    let origin = Repo::init(&root.join("origin")).unwrap();
5138
    let url = root.join("origin").to_string_lossy().to_string();
5139
    let mut repo = Repo::clone(&url, &root.join("r"))
5140
        .unwrap()
5141
        .with_home(root.join("home"));
5142
    let r = root.join("r");
5143
    write(&r, "a.txt", b"a\n");
5144
    let h_a = repo.commit("a", &[]).unwrap();
5145
    assert!(repo.push("origin", false).unwrap()[0].ok);
5146
    origin.refresh().unwrap();
5147
5148
    // A bookmark at the working copy's base, then work on it.
5149
    assert!(repo.bookmark_create("bad name..", None).is_err());
5150
    assert!(repo.bookmark_create("-x", None).is_err());
5151
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
5152
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
5153
    repo.bookmark_switch("feature", false).unwrap();
5154
    assert_eq!(repo.config.bookmark, "feature");
5155
    write(&r, "a.txt", b"a\nb\n");
5156
    write(&r, "b.txt", b"b\n");
5157
    let h_b = repo.commit("b on feature", &[]).unwrap();
5158
    assert_eq!(
5159
        repo.bookmark_heads().unwrap(),
5160
        vec![h_b],
5161
        "b edits a.txt, so it depends on a"
5162
    );
5163
    assert_eq!(
5164
        repo.resolve_heads("main").unwrap(),
5165
        vec![h_a],
5166
        "main is untouched"
5167
    );
5168
    assert_eq!(
5169
        repo.resolve_change("feature").unwrap(),
5170
        h_b,
5171
        "a one-head bookmark names its change"
5172
    );
5173
    // Reopening keeps the workspace's bookmark.
5174
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
5175
    assert_eq!(reopened.config.bookmark, "feature");
5176
    // Back to main: b.txt goes away; work there.
5177
    repo.bookmark_switch("main", false).unwrap();
5178
    assert!(!r.join("b.txt").exists());
5179
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
5180
    write(&r, "c.txt", b"c\n");
5181
    let h_c = repo.commit("c on main", &[]).unwrap();
5182
    let list = repo.bookmarks().unwrap();
5183
    assert_eq!(
5184
        list.iter()
5185
            .map(|b| (b.name.as_str(), b.current))
5186
            .collect::<Vec<_>>(),
5187
        vec![("feature", false), ("main", true)]
5188
    );
5189
    assert_eq!(
5190
        list.iter().find(|b| b.name == "main").unwrap().ahead,
5191
        Some(1),
5192
        "c is not on origin yet"
5193
    );
5194
    // Merge feature into main: the union, both heads, no merge change.
5195
    let m = repo.merge("feature").unwrap();
5196
    assert!(m.changed && m.checked_out);
5197
    let mut want = vec![h_b, h_c];
5198
    want.sort();
5199
    assert_eq!(m.heads, want);
5200
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
5201
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
5202
    assert!(repo.merge("main").is_err());
5203
    // The other bookmark can be pushed by name and appears at origin.
5204
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
5205
    origin.refresh().unwrap();
5206
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
5207
    assert!(repo.push("origin", false).unwrap()[0].ok);
5208
    origin.refresh().unwrap();
5209
    assert_eq!(
5210
        repo.bookmarks()
5211
            .unwrap()
5212
            .iter()
5213
            .find(|b| b.name == "main")
5214
            .unwrap()
5215
            .ahead,
5216
        Some(0)
5217
    );
5218
    // A second workspace inherits the current bookmark and can switch independently.
5219
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
5220
    assert_eq!(ws.config.bookmark, "main");
5221
    let mut ws = ws;
5222
    ws.bookmark_switch("feature", false).unwrap();
5223
    assert_eq!(
5224
        Repo::open(&r).unwrap().config.bookmark,
5225
        "main",
5226
        "the first workspace is unaffected"
5227
    );
5228
    assert!(
5229
        repo.bookmark_delete("feature").is_err(),
5230
        "current bookmark of another workspace"
5231
    );
5232
    ws.bookmark_switch("main", false).unwrap();
5233
    // Set and delete.
5234
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
5235
    assert!(repo.bookmark_delete("main").is_err(), "current here");
5236
    repo.bookmark_delete("feature").unwrap();
5237
    assert!(repo.resolve_heads("feature").is_err());
5238
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
5239
    assert!(
5240
        repo.checkout(&[h_a], false, "checkout").is_ok(),
5241
        "changes of a deleted bookmark remain"
5242
    );
5243
}
5244
5245
#[test]
5246
fn oxygen_subrepos_pin_follow_and_update() {
5247
    hermetic();
5248
    let dir = tempfile::tempdir().unwrap();
5249
    let root = dir.path();
5250
    // A library repository with two commits, and a bare-ish origin for it.
5251
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
5252
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
5253
    let lib = Repo::clone(&lib_url, &root.join("lib"))
5254
        .unwrap()
5255
        .with_home(root.join("home"));
5256
    write(&root.join("lib"), "lib.txt", b"v1\n");
5257
    let l1 = lib.commit("lib v1", &[]).unwrap();
5258
    assert!(lib.push("origin", false).unwrap()[0].ok);
5259
    let _ = lib_origin;
5260
5261
    // The application (a clone of its own origin) adds it as a subrepo.
5262
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
5263
    let app_url = root.join("app-origin").to_string_lossy().to_string();
5264
    let _ = app_origin;
5265
    let app_dir = root.join("app");
5266
    let app = Repo::clone(&app_url, &app_dir)
5267
        .unwrap()
5268
        .with_home(root.join("home"));
5269
    write(&app_dir, "main.txt", b"app\n");
5270
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
5271
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
5272
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
5273
    let snap = app.snapshot("status").unwrap();
5274
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
5275
    assert_eq!(
5276
        paths,
5277
        vec![".oxymodules", "libs/lib", "main.txt"],
5278
        "the nested files are not walked"
5279
    );
5280
    let a1 = app.commit("app with lib", &[]).unwrap();
5281
    let files = app.load_state(&[a1]).unwrap().materialize().files;
5282
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
5283
    assert!(!files.contains_key("libs/lib/lib.txt"));
5284
    assert!(!app.snapshot("status").unwrap().changed);
5285
    let subs = app.subrepos().unwrap();
5286
    assert_eq!(subs.len(), 1);
5287
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
5288
5289
    // Advance the nested repository: the parent sees a modified pin.
5290
    let nested = Repo::open(&app_dir.join("libs/lib"))
5291
        .unwrap()
5292
        .with_home(root.join("home"));
5293
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
5294
    let l2 = nested.commit("lib v2", &[]).unwrap();
5295
    assert!(nested.push("origin", false).unwrap()[0].ok);
5296
    let snap = app.snapshot("status").unwrap();
5297
    assert_eq!(
5298
        snap.statuses
5299
            .iter()
5300
            .map(|s| (s.path.as_str(), s.status))
5301
            .collect::<Vec<_>>(),
5302
        vec![("libs/lib", ChangeStatus::Modified)]
5303
    );
5304
    let a2 = app.commit("bump lib", &[]).unwrap();
5305
    // Checking out the older app state brings the nested working copy back
5306
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
5307
    let r = app.checkout(&[a1], false, "checkout").unwrap();
5308
    assert!(
5309
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
5310
        "{:?}",
5311
        r.notes
5312
    );
5313
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
5314
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
5315
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
5316
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
5317
    assert!(!app.snapshot("status").unwrap().changed);
5318
    // A dirty nested repository is left alone and reported.
5319
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
5320
    let r = app.checkout(&[a2], false, "checkout").unwrap();
5321
    assert!(
5322
        r.notes.iter().any(|n| n.contains("uncommitted")),
5323
        "{:?}",
5324
        r.notes
5325
    );
5326
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
5327
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
5328
    let r = app.submodule_update(false, &[]).unwrap();
5329
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
5330
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
5331
    let _ = l2;
5332
5333
    // A fresh clone of the app has the pin but no nested repository until update --init.
5334
    assert!(app.push("origin", false).unwrap()[0].ok);
5335
    let clone_dir = root.join("app-clone");
5336
    let clone = Repo::clone(&app_url, &clone_dir)
5337
        .unwrap()
5338
        .with_home(root.join("home"));
5339
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
5340
    assert_eq!(
5341
        clone.submodule_update(false, &[]).unwrap(),
5342
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
5343
    );
5344
    assert_eq!(
5345
        clone.submodule_update(true, &[]).unwrap(),
5346
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
5347
    );
5348
    assert_eq!(
5349
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
5350
        b"v2\n"
5351
    );
5352
    assert!(!clone.snapshot("status").unwrap().changed);
5353
    // Removing the subrepo leaves the directory and drops the node.
5354
    clone.submodule_remove("libs/lib").unwrap();
5355
    let snap = clone.snapshot("status").unwrap();
5356
    assert!(
5357
        snap.statuses
5358
            .iter()
5359
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
5360
        "{:?}",
5361
        snap.statuses
5362
    );
5363
    let c = clone.commit("drop lib", &[]).unwrap();
5364
    assert!(!clone
5365
        .load_state(&[c])
5366
        .unwrap()
5367
        .materialize()
5368
        .files
5369
        .contains_key("libs/lib"));
5370
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
5371
    assert!(
5372
        !clone.snapshot("status").unwrap().changed,
5373
        "an unregistered nested repository is ignored"
5374
    );
5375
}
5376
5377
#[test]
5378
fn git_submodules_import_and_export_as_gitlinks() {
5379
    hermetic();
5380
    if std::process::Command::new("git")
5381
        .arg("--version")
5382
        .output()
5383
        .is_err()
5384
    {
5385
        eprintln!("git not installed; skipping");
5386
        return;
5387
    }
5388
    let dir = tempfile::tempdir().unwrap();
5389
    let root = dir.path();
5390
    let git_in = |d: &Path, args: &[&str]| -> String {
5391
        let out = std::process::Command::new("git")
5392
            .arg("-C")
5393
            .arg(d)
5394
            .args([
5395
                "-c",
5396
                "user.name=Grace",
5397
                "-c",
5398
                "[email protected]",
5399
                "-c",
5400
                "commit.gpgsign=false",
5401
                "-c",
5402
                "protocol.file.allow=always",
5403
            ])
5404
            .args(args)
5405
            .output()
5406
            .unwrap();
5407
        assert!(
5408
            out.status.success(),
5409
            "git {args:?}: {}",
5410
            String::from_utf8_lossy(&out.stderr)
5411
        );
5412
        String::from_utf8_lossy(&out.stdout).trim().to_string()
5413
    };
5414
    let sub = root.join("sub");
5415
    fs::create_dir_all(&sub).unwrap();
5416
    git_in(&sub, &["init", "-q", "-b", "main"]);
5417
    write(&sub, "s.txt", b"sub\n");
5418
    git_in(&sub, &["add", "."]);
5419
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
5420
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
5421
    let g = root.join("main.git");
5422
    fs::create_dir_all(&g).unwrap();
5423
    git_in(&g, &["init", "-q", "-b", "main"]);
5424
    write(&g, "README.md", b"# app\n");
5425
    git_in(&g, &["add", "."]);
5426
    git_in(&g, &["commit", "-q", "-m", "initial"]);
5427
    git_in(
5428
        &g,
5429
        &[
5430
            "submodule",
5431
            "add",
5432
            "-q",
5433
            sub.to_str().unwrap(),
5434
            "vendor/sub",
5435
        ],
5436
    );
5437
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
5438
5439
    let dest = root.join("oxy");
5440
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
5441
    let rep = repo.import_git(&g, "main").unwrap();
5442
    assert_eq!((rep.commits, rep.submodules), (2, 1));
5443
    let files = repo
5444
        .load_state(&repo.bookmark_heads().unwrap())
5445
        .unwrap()
5446
        .materialize()
5447
        .files;
5448
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
5449
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
5450
        panic!()
5451
    };
5452
    assert_eq!(
5453
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
5454
        crate::subrepo::Pin::Git {
5455
            sha: sub_sha.clone(),
5456
            branch: "HEAD".into()
5457
        }
5458
    );
5459
    let modules =
5460
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
5461
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
5462
    assert!(modules.entries["vendor/sub"].git);
5463
    assert!(
5464
        files.contains_key(".gitmodules"),
5465
        "the Git file is kept for round trips"
5466
    );
5467
    assert!(
5468
        !dest.join("vendor/sub/.git").exists(),
5469
        "not cloned until update --init"
5470
    );
5471
    assert!(!repo.snapshot("status").unwrap().changed);
5472
    // update --init clones it at the pinned commit; status is unchanged.
5473
    assert_eq!(
5474
        repo.submodule_update(true, &[]).unwrap(),
5475
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
5476
    );
5477
    assert_eq!(
5478
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
5479
        sub_sha
5480
    );
5481
    assert!(!repo.snapshot("status").unwrap().changed);
5482
    // Export writes the gitlink and .gitmodules back.
5483
    let mirror = root.join("mirror.git");
5484
    let rep = repo.git_export(&mirror).unwrap();
5485
    assert_eq!(rep.skipped_subrepos, 0);
5486
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
5487
    assert!(
5488
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
5489
        "{ls}"
5490
    );
5491
    assert_eq!(
5492
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
5493
        ".gitmodules\nREADME.md\nvendor"
5494
    );
5495
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
5496
    assert_eq!(
5497
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
5498
        orig_tree,
5499
        "tree round trip"
5500
    );
5501
}
5502
5503
#[test]
5504
fn partial_commits_by_path_and_by_hunk() {
5505
    hermetic();
5506
    let dir = tempfile::tempdir().unwrap();
5507
    let root = dir.path();
5508
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5509
    write(root, "a.txt", b"1\n2\n3\n");
5510
    write(root, "b.txt", b"b\n");
5511
    let h0 = repo.commit("base", &[]).unwrap();
5512
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
5513
    write(root, "b.txt", b"b\nbb\n");
5514
    write(root, "c.txt", b"c\n");
5515
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
5516
    let h1 = repo
5517
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
5518
        .unwrap();
5519
    let c1 = repo.store().get_change(&h1).unwrap();
5520
    assert!(
5521
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
5522
        "{:?}",
5523
        c1.tree_ops
5524
    );
5525
    assert_eq!(c1.deps, vec![h0]);
5526
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
5527
    assert!(
5528
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
5529
    );
5530
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
5531
    assert!(!files.contains_key("c.txt"));
5532
    let snap = repo.snapshot("status").unwrap();
5533
    assert_eq!(
5534
        snap.statuses
5535
            .iter()
5536
            .map(|s| (s.path.as_str(), s.status))
5537
            .collect::<Vec<_>>(),
5538
        vec![
5539
            ("b.txt", ChangeStatus::Modified),
5540
            ("c.txt", ChangeStatus::Added)
5541
        ]
5542
    );
5543
    assert_eq!(
5544
        fs::read(root.join("b.txt")).unwrap(),
5545
        b"b\nbb\n",
5546
        "disk untouched"
5547
    );
5548
    // By hunk: pick the b.txt insert; c.txt's addition is left.
5549
    let (_, hunks) = repo.hunks().unwrap();
5550
    let b_hunk = hunks
5551
        .iter()
5552
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
5553
        .unwrap()
5554
        .index;
5555
    let h2 = repo
5556
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
5557
        .unwrap();
5558
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
5559
    assert!(
5560
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
5561
    );
5562
    assert!(!files.contains_key("c.txt"));
5563
    let snap = repo.snapshot("status").unwrap();
5564
    assert_eq!(
5565
        snap.statuses
5566
            .iter()
5567
            .map(|s| s.path.as_str())
5568
            .collect::<Vec<_>>(),
5569
        vec!["c.txt"]
5570
    );
5571
    // Choosing only the content hunk of a file in a new directory pulls in
5572
    // the directory and file additions it needs.
5573
    write(root, "d/e.txt", b"e\n");
5574
    let (_, hunks) = repo.hunks().unwrap();
5575
    let e_insert = hunks
5576
        .iter()
5577
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
5578
        .unwrap()
5579
        .index;
5580
    let h3 = repo
5581
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
5582
        .unwrap();
5583
    let c3 = repo.store().get_change(&h3).unwrap();
5584
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
5585
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
5586
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
5587
    // Choosing a new file's addition hunk brings its content along.
5588
    write(root, "f/g.txt", b"g\n");
5589
    let (_, hunks) = repo.hunks().unwrap();
5590
    let g_add = hunks
5591
        .iter()
5592
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
5593
        .unwrap()
5594
        .index;
5595
    let h4 = repo
5596
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
5597
        .unwrap();
5598
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
5599
    assert!(
5600
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
5601
    );
5602
    assert!(!repo
5603
        .snapshot("status")
5604
        .unwrap()
5605
        .statuses
5606
        .iter()
5607
        .any(|s| s.path == "f/g.txt"));
5608
    // Everything left commits normally; the working copy is then clean.
5609
    repo.commit("the rest", &[]).unwrap();
5610
    assert!(!repo.snapshot("status").unwrap().changed);
5611
    let files = repo
5612
        .load_state(&repo.bookmark_heads().unwrap())
5613
        .unwrap()
5614
        .materialize()
5615
        .files;
5616
    assert!(files.contains_key("c.txt"));
5617
}
5618
5619
#[test]
5620
fn blame_attributes_lines_to_introducing_changes_across_renames() {
5621
    hermetic();
5622
    let dir = tempfile::tempdir().unwrap();
5623
    let root = dir.path();
5624
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5625
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
5626
        .unwrap();
5627
    write(root, "a.txt", b"one\n");
5628
    let h1 = repo.commit("first", &[]).unwrap();
5629
    write(root, "a.txt", b"one\ntwo\n");
5630
    let h2 = repo.commit("second", &[]).unwrap();
5631
    let b = repo.blame("a.txt").unwrap();
5632
    assert_eq!(
5633
        b.iter()
5634
            .map(|l| (l.line, l.hash, l.text.as_slice()))
5635
            .collect::<Vec<_>>(),
5636
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
5637
    );
5638
    assert!(b.iter().all(|l| l.author == "Ada"));
5639
    assert_eq!(
5640
        b[0].change_id,
5641
        repo.store().get_change(&h1).unwrap().change_id
5642
    );
5643
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
5644
    repo.commit("rename", &[]).unwrap();
5645
    let b = repo.blame("b.txt").unwrap();
5646
    assert_eq!(
5647
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
5648
        vec![h1, h2],
5649
        "the node survives the rename"
5650
    );
5651
    assert!(repo.blame("a.txt").is_err());
5652
}
5653
5654
#[test]
5655
fn bisect_finds_the_first_bad_change() {
5656
    hermetic();
5657
    let dir = tempfile::tempdir().unwrap();
5658
    let root = dir.path();
5659
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5660
    let mut content = String::new();
5661
    let mut hashes = Vec::new();
5662
    for i in 1..=8 {
5663
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
5664
        write(root, "f.txt", content.as_bytes());
5665
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
5666
    }
5667
    // Each step appends after the previous line, so the chain is linear.
5668
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
5669
    repo.bisect_start().unwrap();
5670
    assert!(matches!(
5671
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
5672
        BisectStep::NeedMarks { good: 1, bad: 0 }
5673
    ));
5674
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
5675
    assert!(
5676
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
5677
        "{step:?}"
5678
    );
5679
    // Automated: bad when the bug line is present.
5680
    let step = repo
5681
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
5682
        .unwrap();
5683
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
5684
    assert_eq!(
5685
        repo.bisect_status().unwrap(),
5686
        Some(BisectStep::Found { culprit: hashes[4] })
5687
    );
5688
    repo.bisect_reset().unwrap();
5689
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
5690
    assert!(repo.bisect_status().unwrap().is_none());
5691
    assert!(!repo.snapshot("status").unwrap().changed);
5692
    // Manual marks and a skip.
5693
    repo.bisect_start().unwrap();
5694
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
5695
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
5696
    let mut skipped_once = false;
5697
    let mut guard = 0;
5698
    while let BisectStep::Testing { .. } = step {
5699
        guard += 1;
5700
        assert!(guard < 20);
5701
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
5702
        if !skipped_once && text.contains("line 6") {
5703
            // An untestable state away from the boundary: the search routes around it.
5704
            skipped_once = true;
5705
            step = repo.bisect_mark(None, &[]).unwrap();
5706
            continue;
5707
        }
5708
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
5709
    }
5710
    assert!(skipped_once);
5711
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
5712
    repo.bisect_reset().unwrap();
5713
    // Skipping the culprit itself leaves it among the candidates reported.
5714
    repo.bisect_start().unwrap();
5715
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
5716
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
5717
    let mut guard = 0;
5718
    while let BisectStep::Testing { heads, .. } = &step {
5719
        guard += 1;
5720
        assert!(guard < 20);
5721
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
5722
        let is_culprit_state =
5723
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
5724
        step = if is_culprit_state {
5725
            repo.bisect_mark(None, &[]).unwrap()
5726
        } else {
5727
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
5728
        };
5729
    }
5730
    match step {
5731
        BisectStep::Inconclusive { candidates } => assert!(
5732
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
5733
            "{candidates:?}"
5734
        ),
5735
        other => panic!("{other:?}"),
5736
    }
5737
    repo.bisect_reset().unwrap();
5738
}
5739
5740
#[test]
5741
fn squash_folds_a_change_into_its_dependency() {
5742
    hermetic();
5743
    let dir = tempfile::tempdir().unwrap();
5744
    let root = dir.path();
5745
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5746
    write(root, "a.txt", b"1\n");
5747
    let a = repo.commit("A", &[]).unwrap();
5748
    write(root, "a.txt", b"1\n2\n");
5749
    let c = repo.commit("C", &[]).unwrap();
5750
    write(root, "a.txt", b"1\n2\n3\n");
5751
    let e = repo.commit("E", &[]).unwrap();
5752
    write(root, "b.txt", b"b\n");
5753
    let b = repo.commit("B", &[]).unwrap();
5754
    let id_a = repo.store().get_change(&a).unwrap().change_id;
5755
    let id_e = repo.store().get_change(&e).unwrap().change_id;
5756
    // E depends on C which A lacks: refused, naming it.
5757
    let err = repo.squash(&e, &a).unwrap_err().to_string();
5758
    assert!(err.contains(&c.short(12)), "{err}");
5759
    // C into A: A' has both, C is gone, E follows and still reads the same.
5760
    let a2 = repo.squash(&c, &a).unwrap();
5761
    let a2c = repo.store().get_change(&a2).unwrap();
5762
    assert_eq!(a2c.change_id, id_a);
5763
    assert!(a2c.deps.is_empty());
5764
    let heads = repo.bookmark_heads().unwrap();
5765
    let st = repo.load_state(&heads).unwrap();
5766
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
5767
    let e2 = st
5768
        .changes()
5769
        .find(|(_, m)| m.change_id == id_e)
5770
        .map(|(h, _)| *h)
5771
        .unwrap();
5772
    assert_eq!(
5773
        repo.store().get_change(&e2).unwrap().deps,
5774
        vec![a2],
5775
        "E now depends on A' alone"
5776
    );
5777
    let files = st.materialize().files;
5778
    assert!(
5779
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
5780
    );
5781
    assert!(files.contains_key("b.txt"));
5782
    assert!(st.contains(&b));
5783
    assert!(!repo.snapshot("status").unwrap().changed);
5784
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
5785
    // Undo restores the three original changes.
5786
    repo.undo().unwrap();
5787
    repo.undo().unwrap();
5788
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
5789
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
5790
}
5791
5792
#[test]
5793
fn rebase_re_expresses_a_change_against_another_base() {
5794
    hermetic();
5795
    let dir = tempfile::tempdir().unwrap();
5796
    let root = dir.path();
5797
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5798
    write(root, "a.txt", b"1\n2\n");
5799
    let a = repo.commit("A", &[]).unwrap();
5800
    write(root, "a.txt", b"1\n2\n3\n");
5801
    let c = repo.commit("C: append 3", &[]).unwrap();
5802
    write(root, "a.txt", b"1\n2\n3\n4\n");
5803
    let e = repo.commit("E: append 4", &[]).unwrap();
5804
    // A different base: A plus a change that prepends a line.
5805
    repo.checkout(&[a], true, "checkout").unwrap();
5806
    write(root, "a.txt", b"0\n1\n2\n");
5807
    let d = repo.commit("D: prepend 0", &[]).unwrap();
5808
    let id_c = repo.store().get_change(&c).unwrap().change_id;
5809
    let id_e = repo.store().get_change(&e).unwrap().change_id;
5810
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
5811
    let c2 = repo.rebase(&c, &[d]).unwrap();
5812
    let c2c = repo.store().get_change(&c2).unwrap();
5813
    assert_eq!(c2c.change_id, id_c);
5814
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
5815
    let heads = repo.bookmark_heads().unwrap();
5816
    let st = repo.load_state(&heads).unwrap();
5817
    assert!(!st.contains(&c) && st.contains(&d));
5818
    let e2 = st
5819
        .changes()
5820
        .find(|(_, m)| m.change_id == id_e)
5821
        .map(|(h, _)| *h)
5822
        .unwrap();
5823
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
5824
    assert!(
5825
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
5826
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
5827
    );
5828
    let files = st.materialize().files;
5829
    assert!(
5830
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
5831
        "{:?}",
5832
        files["a.txt"].content
5833
    );
5834
    assert!(!files["a.txt"].is_conflicted());
5835
    // Rebasing onto a state that already contains the change is refused.
5836
    assert!(repo.rebase(&c2, &[c2]).is_err());
5837
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
5838
    assert!(
5839
        err.contains("lacks dependencies"),
5840
        "E needs C, which D's state does not have: {err}"
5841
    );
5842
}
5843
5844
#[test]
5845
fn unsigned_tags_keep_their_message() {
5846
    hermetic();
5847
    let dir = tempfile::tempdir().unwrap();
5848
    let root = dir.path();
5849
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5850
    write(root, "a.txt", b"a\n");
5851
    repo.commit("a", &[]).unwrap();
5852
    assert!(repo.secret_key().unwrap().is_none());
5853
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
5854
        .unwrap();
5855
    let tags = repo.tags().unwrap();
5856
    assert_eq!(
5857
        (
5858
            tags[0].name.as_str(),
5859
            tags[0].message.as_str(),
5860
            tags[0].signer.as_deref()
5861
        ),
5862
        ("v1", "first release", None)
5863
    );
5864
    assert!(
5865
        repo.tag_refs().unwrap()[0].attestation.is_none(),
5866
        "an unsigned attestation is not advertised"
5867
    );
5868
}
5869
5870
#[test]
5871
fn fsck_passes_a_sound_repository_and_names_each_fault() {
5872
    // Files on disk are what this tests: tampering with them, and the
5873
    // directory store's crash points.
5874
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
5875
        return;
5876
    }
5877
    hermetic();
5878
    let dir = tempfile::tempdir().unwrap();
5879
    let root = dir.path();
5880
    let origin_path = root.join("origin");
5881
    let origin = Repo::init(&origin_path).unwrap();
5882
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
5883
        .unwrap()
5884
        .with_home(root.join("home-a"));
5885
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5886
        .unwrap();
5887
    write(&root.join("a"), "f.txt", b"one\n");
5888
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
5889
    let h1 = a.commit("first", &[]).unwrap();
5890
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
5891
    let h2 = a.commit("second", &[]).unwrap();
5892
    a.tag_create("v1", &[h2], "first release").unwrap();
5893
    a.checkpoint().unwrap();
5894
    assert!(a.push("origin", false).unwrap()[0].ok);
5895
    origin.refresh().unwrap();
5896
5897
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
5898
    for repo in [&a, &origin] {
5899
        let rep = repo.fsck().unwrap();
5900
        assert_eq!(rep.problems, vec![], "{rep:?}");
5901
        // The two commits, plus the working copy's change in `a`.
5902
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
5903
        assert!(rep.ops > 1 && rep.objects > 5);
5904
    }
5905
    assert!(origin.fsck().unwrap().attestations >= 1);
5906
5907
    // A flipped byte in a stored object is corruption, named by hash.
5908
    let c1 = a.store().path_for(&h1);
5909
    let pristine = fs::read(&c1).unwrap();
5910
    let mut bytes = pristine.clone();
5911
    *bytes.last_mut().unwrap() ^= 1;
5912
    fs::write(&c1, &bytes).unwrap();
5913
    let rep = a.fsck().unwrap();
5914
    assert!(rep.errors() >= 1);
5915
    assert!(
5916
        rep.problems
5917
            .iter()
5918
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
5919
        "{rep:?}"
5920
    );
5921
    fs::write(&c1, &pristine).unwrap();
5922
    assert_eq!(a.fsck().unwrap().errors(), 0);
5923
5924
    // A missing change is named with what needed it.
5925
    fs::remove_file(&c1).unwrap();
5926
    let rep = a.fsck().unwrap();
5927
    assert!(
5928
        rep.problems.iter().any(|p| p.severity == Severity::Error
5929
            && p.object == Some(h1)
5930
            && p.what.contains("change missing, needed by change")),
5931
        "{rep:?}"
5932
    );
5933
    fs::write(&c1, &pristine).unwrap();
5934
5935
    // A missing blob is an error in a full clone.
5936
    let c2 = a.store().get_change(&h1).unwrap();
5937
    let blob = c2
5938
        .edits
5939
        .iter()
5940
        .find_map(|e| match e {
5941
            Edit::Replace { new: Some(b), .. } => Some(*b),
5942
            _ => None,
5943
        })
5944
        .expect("the binary file is a blob");
5945
    let bp = a.store().path_for(&blob);
5946
    let blob_bytes = fs::read(&bp).unwrap();
5947
    fs::remove_file(&bp).unwrap();
5948
    let rep = a.fsck().unwrap();
5949
    assert!(
5950
        rep.problems
5951
            .iter()
5952
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
5953
        "{rep:?}"
5954
    );
5955
    fs::write(&bp, &blob_bytes).unwrap();
5956
5957
    // A broken op log head is reported, not a crash.
5958
    let head = root.join("a/.oxy/ops/head");
5959
    let saved = fs::read(&head).unwrap();
5960
    fs::write(&head, b"not a hash").unwrap();
5961
    let rep = a.fsck().unwrap();
5962
    assert!(
5963
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
5964
        "{rep:?}"
5965
    );
5966
    fs::write(&head, saved).unwrap();
5967
    assert_eq!(a.fsck().unwrap().problems, vec![]);
5968
}
5969
5970
/// Copy a directory tree (for restoring a pristine repository).
5971
fn copy_tree(from: &Path, to: &Path) {
5972
    fs::create_dir_all(to).unwrap();
5973
    for e in fs::read_dir(from).unwrap() {
5974
        let e = e.unwrap();
5975
        let target = to.join(e.file_name());
5976
        if e.file_type().unwrap().is_dir() {
5977
            copy_tree(&e.path(), &target);
5978
        } else {
5979
            fs::copy(e.path(), &target).unwrap();
5980
        }
5981
    }
5982
}
5983
5984
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
5985
/// would, and check that both repositories still open, pass `fsck`, and
5986
/// accept the same operation again.
5987
#[test]
5988
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
5989
    // Files on disk are what this tests: tampering with them, and the
5990
    // directory store's crash points.
5991
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
5992
        return;
5993
    }
5994
    use crate::durable::failpoint;
5995
    hermetic();
5996
    let dir = tempfile::tempdir().unwrap();
5997
    let pristine = dir.path().join("pristine");
5998
    let origin_path = pristine.join("origin");
5999
    Repo::init(&origin_path).unwrap();
6000
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
6001
        .unwrap()
6002
        .with_home(dir.path().join("home"));
6003
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6004
        .unwrap();
6005
    write(&pristine.join("a"), "f.txt", b"one\n");
6006
    a.commit("first", &[]).unwrap();
6007
    assert!(a.push("origin", false).unwrap()[0].ok);
6008
    drop(a);
6009
6010
    type Op = fn(&Repo) -> Result<()>;
6011
    let edit_and_commit: Op = |r| {
6012
        write(r.root(), "f.txt", b"one\ntwo\n");
6013
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
6014
        r.commit("second", &[]).map(|_| ())
6015
    };
6016
    let push: Op = |r| {
6017
        let res = r.push("origin", false)?;
6018
        if res.iter().all(|x| x.ok) {
6019
            Ok(())
6020
        } else {
6021
            Err(RepoError::Msg(format!("{res:?}")))
6022
        }
6023
    };
6024
6025
    for (name, prepare, op) in [
6026
        ("commit", None, edit_and_commit),
6027
        ("push", Some(edit_and_commit), push),
6028
    ] {
6029
        let mut steps = 0;
6030
        for n in 1.. {
6031
            let run = dir.path().join(format!("{name}-{n}"));
6032
            copy_tree(&pristine, &run);
6033
            // Clones record their remote by path; point it at this copy.
6034
            let open = |p: &Path| {
6035
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
6036
                r.config
6037
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
6038
                    .unwrap();
6039
                r.save_config().unwrap();
6040
                r
6041
            };
6042
            let a = open(&run.join("a"));
6043
            if let Some(prep) = prepare {
6044
                prep(&a).unwrap();
6045
            }
6046
            failpoint::crash_after(n);
6047
            let outcome = op(&a);
6048
            let crashed = failpoint::disarm();
6049
            drop(a);
6050
            if !crashed {
6051
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
6052
                steps = n - 1;
6053
                break;
6054
            }
6055
            assert!(
6056
                outcome.is_err(),
6057
                "{name}: a crash at step {n} was swallowed"
6058
            );
6059
            for repo in ["a", "origin"] {
6060
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
6061
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
6062
                });
6063
                let rep = r.fsck().unwrap();
6064
                assert_eq!(
6065
                    rep.errors(),
6066
                    0,
6067
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
6068
                    rep.problems
6069
                );
6070
            }
6071
            // The interrupted operation can simply be run again.
6072
            let a = open(&run.join("a"));
6073
            // A crash after the commit point leaves the commit done.
6074
            let landed = a
6075
                .bookmark_heads()
6076
                .unwrap()
6077
                .iter()
6078
                .any(|h| a.store().get_change(h).unwrap().message == "second");
6079
            let again = match (name, landed) {
6080
                ("commit", true) => Ok(()),
6081
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
6082
                _ => op(&a),
6083
            };
6084
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
6085
            assert_eq!(a.fsck().unwrap().errors(), 0);
6086
            fs::remove_dir_all(&run).unwrap();
6087
        }
6088
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
6089
    }
6090
}
6091
6092
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
6093
/// running at the same time lose nothing: every commit ends up on the
6094
/// bookmark, locally and on the remote, and the repository passes fsck.
6095
#[test]
6096
fn concurrent_commits_in_two_workspaces_lose_nothing() {
6097
    hermetic();
6098
    let dir = tempfile::tempdir().unwrap();
6099
    let root = dir.path();
6100
    let origin = root.join("origin");
6101
    Repo::init_bare_unbound(&origin).unwrap();
6102
    let main = root.join("main");
6103
    let mut repo = Repo::init(&main).unwrap();
6104
    repo.config
6105
        .set("remote.origin.url", &origin.to_string_lossy())
6106
        .unwrap();
6107
    repo.save_config().unwrap();
6108
    write(&main, "seed.txt", b"seed\n");
6109
    repo.commit("seed", &[]).unwrap();
6110
    let second = root.join("second");
6111
    repo.workspace_add(&second, None).unwrap();
6112
    drop(repo);
6113
6114
    const EACH: usize = 15;
6115
    std::thread::scope(|s| {
6116
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
6117
            s.spawn(move || {
6118
                let r = Repo::open(&dir).unwrap();
6119
                for i in 0..EACH {
6120
                    write(
6121
                        &dir,
6122
                        &format!("{tag}-{i}.txt"),
6123
                        format!("{tag} {i}\n").as_bytes(),
6124
                    );
6125
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
6126
                    if push && i % 5 == 4 {
6127
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
6128
                        let _ = r.push("origin", false);
6129
                    }
6130
                }
6131
            });
6132
        }
6133
    });
6134
6135
    let repo = Repo::open(&main).unwrap();
6136
    let heads = repo.bookmark_heads().unwrap();
6137
    let state = repo.load_state(&heads).unwrap();
6138
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
6139
    for tag in ["a", "b"] {
6140
        for i in 0..EACH {
6141
            assert!(
6142
                messages.contains(&format!("{tag} {i}")),
6143
                "lost commit {tag} {i}; have {messages:?}"
6144
            );
6145
        }
6146
    }
6147
    let rep = repo.fsck().unwrap();
6148
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
6149
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
6150
    let hosted = Repo::open(&origin).unwrap();
6151
    let hosted_heads = hosted.bookmark_heads().unwrap();
6152
    assert_eq!(
6153
        hosted.load_state(&hosted_heads).unwrap().len(),
6154
        state.len(),
6155
        "the remote has every commit"
6156
    );
6157
}
6158
6159
/// Two operations recorded from the same parent (what two processes do
6160
/// when they race) are merged: both bookmarks' heads survive, and a
6161
/// change made on one side only is kept.
6162
#[test]
6163
fn operations_from_the_same_parent_are_merged() {
6164
    hermetic();
6165
    let dir = tempfile::tempdir().unwrap();
6166
    let root = dir.path();
6167
    let repo = Repo::init(root).unwrap();
6168
    write(root, "a.txt", b"a\n");
6169
    let a = repo.commit("a", &[]).unwrap();
6170
    write(root, "b.txt", b"b\n");
6171
    let b = repo.commit("b", &[]).unwrap();
6172
    let (x, op) = repo.head_op().unwrap();
6173
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
6174
6175
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
6176
    let mut one = op.view.clone();
6177
    one.bookmarks.insert("main".into(), state(vec![a]));
6178
    one.bookmarks.insert("topic".into(), state(vec![a]));
6179
    let mut two = op.view.clone();
6180
    two.bookmarks.insert("main".into(), state(vec![b]));
6181
    repo.record_op(&[x], "one", one).unwrap();
6182
    let merged = repo.record_op(&[x], "two", two).unwrap();
6183
6184
    let (head, op) = repo.head_op().unwrap();
6185
    assert_eq!(head, merged);
6186
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
6187
    assert!(op.command.contains("merged with a concurrent operation"));
6188
    let mut main = repo
6189
        .store()
6190
        .get_state(&op.view.bookmarks["main"])
6191
        .unwrap()
6192
        .heads;
6193
    main.sort();
6194
    let mut want = vec![a, b];
6195
    want.sort();
6196
    assert_eq!(main, want, "both sides' heads are kept");
6197
    assert!(
6198
        op.view.bookmarks.contains_key("topic"),
6199
        "a one-sided change survives"
6200
    );
6201
    assert_eq!(repo.fsck().unwrap().errors(), 0);
6202
}
6203
6204
#[test]
6205
fn failed_requests_come_with_a_next_step() {
6206
    use crate::protocol::hint_for;
6207
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
6208
        .unwrap()
6209
        .contains("token"));
6210
    assert!(hint_for("…: HTTP 403: forbidden")
6211
        .unwrap()
6212
        .contains("repo:write"));
6213
    assert!(hint_for("…: HTTP 404: no such repository")
6214
        .unwrap()
6215
        .contains("owner and repository name"));
6216
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
6217
        .unwrap()
6218
        .contains("oxyhub-ca.pem"));
6219
    assert!(hint_for("Connect error: Connection refused (os error 111)")
6220
        .unwrap()
6221
        .contains("running"));
6222
    assert!(hint_for("Dns Failed: failed to lookup address information")
6223
        .unwrap()
6224
        .contains("resolve"));
6225
    assert_eq!(hint_for("something else entirely"), None);
6226
}
6227
6228
#[test]
6229
fn doctor_names_problems_and_what_to_do() {
6230
    hermetic();
6231
    let dir = tempfile::tempdir().unwrap();
6232
    let root = dir.path();
6233
    let origin = root.join("origin");
6234
    Repo::init_bare_unbound(&origin).unwrap();
6235
    let mut repo = Repo::init(&root.join("r"))
6236
        .unwrap()
6237
        .with_home(root.join("home"));
6238
    let find = |r: &DoctorReport, area: &str, h: Health| {
6239
        r.checks
6240
            .iter()
6241
            .find(|c| c.area == area && c.health == h)
6242
            .cloned()
6243
    };
6244
6245
    let r = repo.doctor(true);
6246
    assert!(find(&r, "identity", Health::Warn)
6247
        .unwrap()
6248
        .hint
6249
        .unwrap()
6250
        .contains("oxy identity create"));
6251
    assert!(find(&r, "repository", Health::Ok).is_some());
6252
    // oxygen#127: no policy is said, with who sets one.
6253
    assert!(find(&r, "trust", Health::Warn)
6254
        .unwrap()
6255
        .hint
6256
        .unwrap()
6257
        .contains("oxy policy init"));
6258
6259
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6260
        .unwrap();
6261
    repo.policy_init().unwrap();
6262
    let r = repo.doctor(false);
6263
    let trust = find(&r, "trust", Health::Ok).expect("a fresh policy is fine");
6264
    assert!(
6265
        trust.message.contains("serial 1") && trust.message.contains("1 root"),
6266
        "{trust:?}"
6267
    );
6268
    repo.config.set("author.name", "Ada").unwrap();
6269
    repo.config.set("author.email", "[email protected]").unwrap();
6270
    repo.config
6271
        .set("remote.origin.url", &origin.to_string_lossy())
6272
        .unwrap();
6273
    repo.config
6274
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
6275
        .unwrap();
6276
    repo.config.set("remote.down.token", "t").unwrap();
6277
    repo.config
6278
        .set("remote.badca.url", "https://example.invalid/a/b")
6279
        .unwrap();
6280
    repo.config
6281
        .set(
6282
            "remote.badca.ca",
6283
            &root.join("missing.pem").to_string_lossy(),
6284
        )
6285
        .unwrap();
6286
    repo.save_config().unwrap();
6287
6288
    let r = repo.doctor(true);
6289
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
6290
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
6291
    assert!(find(&r, "remote origin", Health::Ok)
6292
        .unwrap()
6293
        .message
6294
        .contains("first push binds it"));
6295
    let down = find(&r, "remote down", Health::Fail).unwrap();
6296
    assert!(
6297
        down.hint.as_deref().unwrap_or("").contains("running"),
6298
        "{down:?}"
6299
    );
6300
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
6301
    assert!(
6302
        badca.hint.unwrap().contains("remote.badca.ca"),
6303
        "the remote's own name is in the hint"
6304
    );
6305
    assert_eq!(r.worst(), Health::Fail);
6306
6307
    // Offline, nothing is contacted.
6308
    let r = repo.doctor(false);
6309
    assert!(find(&r, "remote down", Health::Fail).is_none());
6310
    assert!(find(&r, "remote down", Health::Ok)
6311
        .unwrap()
6312
        .message
6313
        .contains("not contacted"));
6314
}
6315
6316
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
6317
/// after it. Inserting after `b` and then deleting `b`, one commit after
6318
/// the other, must not leave a delete/insert conflict.
6319
#[test]
6320
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
6321
    hermetic();
6322
    let dir = tempfile::tempdir().unwrap();
6323
    let root = dir.path();
6324
    let repo = Repo::init(root).unwrap();
6325
    write(root, "f", b"a\nb\nc\n");
6326
    repo.commit("base", &[]).unwrap();
6327
    write(root, "f", b"a\nb\nx\nc\n");
6328
    let insert = repo.commit("insert x after b", &[]).unwrap();
6329
    write(root, "f", b"a\nx\nc\n");
6330
    let delete = repo.commit("delete b", &[]).unwrap();
6331
    assert!(
6332
        repo.store()
6333
            .get_change(&delete)
6334
            .unwrap()
6335
            .deps
6336
            .contains(&insert),
6337
        "the deletion depends on the insertion below the deleted line"
6338
    );
6339
    let heads = repo.bookmark_heads().unwrap();
6340
    assert_eq!(heads, vec![delete]);
6341
    let snap = repo.load_state(&heads).unwrap().materialize();
6342
    assert!(!snap.is_conflicted());
6343
    assert!(
6344
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
6345
    );
6346
}
6347
6348
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
6349
/// replacement depends on the change that set the blob it replaces.
6350
#[test]
6351
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
6352
    hermetic();
6353
    let dir = tempfile::tempdir().unwrap();
6354
    let root = dir.path();
6355
    let repo = Repo::init(root).unwrap();
6356
    write(root, "bin", b"\0A");
6357
    let v1 = repo.commit("v1", &[]).unwrap();
6358
    write(root, "bin", b"\0B");
6359
    let v2 = repo.commit("v2", &[]).unwrap();
6360
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
6361
    write(root, "bin", b"\0A");
6362
    let v3 = repo.commit("back to A", &[]).unwrap();
6363
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
6364
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
6365
    let state = repo.load_state(&[v3]).unwrap();
6366
    let snap = state.materialize();
6367
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
6368
        panic!("opaque")
6369
    };
6370
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
6371
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
6372
}
6373
6374
/// Spec §23: a binary file changed on two branches and merged in Git to
6375
/// one side's version comes back as that version at the merge, and the
6376
/// import verifies commit by commit.
6377
#[test]
6378
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
6379
    hermetic();
6380
    if std::process::Command::new("git")
6381
        .arg("--version")
6382
        .output()
6383
        .is_err()
6384
    {
6385
        eprintln!("git not installed; skipping");
6386
        return;
6387
    }
6388
    let dir = tempfile::tempdir().unwrap();
6389
    let root = dir.path();
6390
    let g = root.join("src.git");
6391
    fs::create_dir_all(&g).unwrap();
6392
    let git = |args: &[&str]| -> String {
6393
        let out = std::process::Command::new("git")
6394
            .arg("-C")
6395
            .arg(&g)
6396
            .args([
6397
                "-c",
6398
                "user.name=Grace",
6399
                "-c",
6400
                "[email protected]",
6401
                "-c",
6402
                "commit.gpgsign=false",
6403
            ])
6404
            .args(args)
6405
            .output()
6406
            .unwrap();
6407
        assert!(
6408
            out.status.success(),
6409
            "git {args:?}: {}",
6410
            String::from_utf8_lossy(&out.stderr)
6411
        );
6412
        String::from_utf8_lossy(&out.stdout).trim().to_string()
6413
    };
6414
    git(&["init", "-q", "-b", "main"]);
6415
    write(&g, "logo.bin", b"\0base");
6416
    write(&g, "notes.txt", b"a\nb\nc\n");
6417
    git(&["add", "."]);
6418
    git(&["commit", "-qm", "base"]);
6419
    git(&["checkout", "-qb", "side"]);
6420
    write(&g, "logo.bin", b"\0side");
6421
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
6422
    git(&["commit", "-qam", "side"]);
6423
    git(&["checkout", "-q", "main"]);
6424
    write(&g, "logo.bin", b"\0main");
6425
    git(&["commit", "-qam", "main"]);
6426
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
6427
    let _ = std::process::Command::new("git")
6428
        .arg("-C")
6429
        .arg(&g)
6430
        .args([
6431
            "-c",
6432
            "user.name=G",
6433
            "-c",
6434
            "user.email=g@e",
6435
            "merge",
6436
            "-q",
6437
            "side",
6438
        ])
6439
        .output();
6440
    write(&g, "logo.bin", b"\0main");
6441
    git(&["add", "."]);
6442
    git(&["commit", "-qm", "merge side"]);
6443
    // Then a revert of the binary to its first version.
6444
    write(&g, "logo.bin", b"\0base");
6445
    git(&["commit", "-qam", "back to base"]);
6446
6447
    let repo = Repo::init(&root.join("o")).unwrap();
6448
    let rep = repo.import_git(&g, "main").unwrap();
6449
    assert_eq!(rep.merges, 1);
6450
    let v = repo.verify_git_import(&g, "main").unwrap();
6451
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6452
    assert_eq!(v.commits, 5);
6453
    let snap = repo
6454
        .load_state(&repo.bookmark_heads().unwrap())
6455
        .unwrap()
6456
        .materialize();
6457
    assert!(!snap.is_conflicted());
6458
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
6459
        panic!("opaque")
6460
    };
6461
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
6462
}
6463
6464
/// Spec §7.7 on a file system without executable bits or symlinks: the
6465
/// recorded bit is kept, and a symlink checked out as a plain file holding
6466
/// its target is still that symlink.
6467
#[cfg(unix)]
6468
#[test]
6469
fn windows_file_systems_keep_exec_bits_and_symlinks() {
6470
    use crate::portable::Platform;
6471
    use std::os::unix::fs::PermissionsExt;
6472
    hermetic();
6473
    let dir = tempfile::tempdir().unwrap();
6474
    let root = dir.path();
6475
    let repo = Repo::init(root).unwrap();
6476
    write(root, "run.sh", b"#!/bin/sh\n");
6477
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
6478
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
6479
    repo.commit("script and link", &[]).unwrap();
6480
    drop(repo);
6481
6482
    // What checking out on Windows leaves: no exec bit, the link as a file.
6483
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
6484
    fs::remove_file(root.join("link")).unwrap();
6485
    write(root, "link", b"run.sh");
6486
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
6487
    let s = win.snapshot("oxy status").unwrap();
6488
    assert!(
6489
        s.statuses.is_empty(),
6490
        "nothing changed on Windows: {:?}",
6491
        statuses(&s)
6492
    );
6493
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
6494
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
6495
    write(root, "link", b"other");
6496
    let h = win.commit("edit on Windows", &[]).unwrap();
6497
    let snap = win.load_state(&[h]).unwrap().materialize();
6498
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
6499
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
6500
    // The same working copy read as Linux sees the lost bit and the plain file.
6501
    let linux = Repo::open(root).unwrap();
6502
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
6503
}
6504
6505
/// Paths that collide on case-insensitive or Windows file systems are
6506
/// named at checkout there, and by doctor everywhere.
6507
#[test]
6508
fn paths_other_platforms_cannot_hold_are_reported() {
6509
    use crate::portable::Platform;
6510
    hermetic();
6511
    let dir = tempfile::tempdir().unwrap();
6512
    let root = dir.path();
6513
    let repo = Repo::init(root).unwrap();
6514
    write(root, "README.md", b"a\n");
6515
    write(root, "readme.md", b"b\n");
6516
    write(root, "src/aux.c", b"int x;\n");
6517
    let h = repo.commit("unportable", &[]).unwrap();
6518
    let r = repo.doctor(false);
6519
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
6520
    assert_eq!(port.health, Health::Warn);
6521
    assert!(
6522
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
6523
        "{}",
6524
        port.message
6525
    );
6526
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
6527
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
6528
    assert!(
6529
        rep.notes
6530
            .iter()
6531
            .any(|n| n.contains("README.md and readme.md")),
6532
        "{:?}",
6533
        rep.notes
6534
    );
6535
    assert!(
6536
        !rep.notes.iter().any(|n| n.contains("aux.c")),
6537
        "macOS allows aux.c"
6538
    );
6539
}
6540
6541
#[test]
6542
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
6543
    hermetic();
6544
    let dir = tempfile::tempdir().unwrap();
6545
    let repo = Repo::init(dir.path()).unwrap();
6546
    write(dir.path(), "a.txt", b"one\n");
6547
    write(dir.path(), "other.txt", b"x\n");
6548
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
6549
    repo.snapshot("t").unwrap();
6550
    let c1 = repo.commit("first", &[]).unwrap();
6551
    write(dir.path(), "other.txt", b"y\n");
6552
    repo.snapshot("t").unwrap();
6553
    repo.commit("other only", &[]).unwrap();
6554
    write(dir.path(), "a.txt", b"one\ntwo\n");
6555
    repo.snapshot("t").unwrap();
6556
    let c3 = repo.commit("second line", &[]).unwrap();
6557
    write(dir.path(), "other.txt", b"z\n");
6558
    repo.snapshot("t").unwrap();
6559
    repo.commit("other again", &[]).unwrap();
6560
6561
    let heads = repo.bookmark_heads().unwrap();
6562
    let state = repo.load_state(&heads).unwrap();
6563
    let full: Vec<ChangeHash> = repo
6564
        .log_for_path_in("a.txt", &heads)
6565
        .unwrap()
6566
        .iter()
6567
        .map(|e| e.hash)
6568
        .collect();
6569
    assert_eq!(
6570
        full,
6571
        vec![c3, c1],
6572
        "newest first, only changes touching the path"
6573
    );
6574
    let newest: Vec<ChangeHash> = repo
6575
        .log_for_path_of(&state, "a.txt", Some(1))
6576
        .unwrap()
6577
        .iter()
6578
        .map(|e| e.hash)
6579
        .collect();
6580
    assert_eq!(newest, vec![c3], "stops at the first");
6581
    assert_eq!(
6582
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
6583
        2
6584
    );
6585
    assert!(repo
6586
        .log_for_path_of(&state, "missing.txt", Some(1))
6587
        .is_err());
6588
    assert_eq!(
6589
        repo.log_state(&heads).unwrap().len(),
6590
        repo.log_of(&state).len()
6591
    );
6592
6593
    let tree = state.tree().view();
6594
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
6595
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
6596
    assert_eq!(
6597
        via_state
6598
            .iter()
6599
            .map(|l| (l.hash, l.text.clone()))
6600
            .collect::<Vec<_>>(),
6601
        via_heads
6602
            .iter()
6603
            .map(|l| (l.hash, l.text.clone()))
6604
            .collect::<Vec<_>>()
6605
    );
6606
    assert_eq!(
6607
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
6608
        vec![c1, c3]
6609
    );
6610
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
6611
}
6612
6613
/// A text file whose stat matches the manifest and whose recorded hash is
6614
/// the base's content is taken from the base without reading it; anything
6615
/// else is read, so no edit is missed (spec §12.3).
6616
#[cfg(unix)]
6617
#[test]
6618
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
6619
    use std::os::unix::fs::PermissionsExt;
6620
    hermetic();
6621
    let dir = tempfile::tempdir().unwrap();
6622
    let root = dir.path();
6623
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6624
    write(root, "a.txt", b"one\ntwo\n");
6625
    write(root, "b.txt", b"bee\n");
6626
    repo.commit("base", &[]).unwrap();
6627
    let age = |p: &str| {
6628
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6629
        fs::File::options()
6630
            .write(true)
6631
            .open(root.join(p))
6632
            .unwrap()
6633
            .set_modified(old)
6634
            .unwrap();
6635
    };
6636
    age("a.txt");
6637
    age("b.txt");
6638
    assert!(
6639
        !repo.snapshot("status").unwrap().changed,
6640
        "records the aged stat"
6641
    );
6642
6643
    // Clean and equal to the base: not read at all.
6644
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6645
    let snap = repo.snapshot("status").unwrap();
6646
    assert!(
6647
        !snap.changed && snap.statuses.is_empty(),
6648
        "{:?}",
6649
        snap.statuses
6650
    );
6651
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6652
6653
    // An uncommitted edit that is older than the manifest: stat-clean, but
6654
    // its hash is not the base's, so it is read and stays visible.
6655
    write(root, "b.txt", b"bee edited\n");
6656
    age("b.txt");
6657
    let first = repo.snapshot("status").unwrap();
6658
    assert_eq!(
6659
        statuses(&first),
6660
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
6661
    );
6662
    let again = repo.snapshot("status").unwrap();
6663
    assert_eq!(
6664
        statuses(&again),
6665
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
6666
        "still seen once stat-clean"
6667
    );
6668
    assert!(!again.changed, "and the working copy hashes the same");
6669
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6670
    assert!(
6671
        repo.snapshot("status").is_err(),
6672
        "an edited file must be read, never taken from the base"
6673
    );
6674
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6675
6676
    // A same-size edit made just now is racy and read.
6677
    write(root, "a.txt", b"one\nTWO\n");
6678
    assert_eq!(
6679
        statuses(&repo.snapshot("status").unwrap()),
6680
        vec![
6681
            ("a.txt".to_string(), ChangeStatus::Modified),
6682
            ("b.txt".to_string(), ChangeStatus::Modified)
6683
        ]
6684
    );
6685
    // Committing makes the edits the base: both are clean and served from it again.
6686
    repo.commit("edits", &[]).unwrap();
6687
    age("a.txt");
6688
    age("b.txt");
6689
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
6690
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6691
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6692
    let snap = repo.snapshot("status").unwrap();
6693
    assert!(!snap.changed && snap.statuses.is_empty());
6694
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6695
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6696
}
6697
6698
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
6699
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
6700
/// file is unchanged, and loading through the checkpoint equals a full load.
6701
#[test]
6702
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
6703
    hermetic();
6704
    let dir = tempfile::tempdir().unwrap();
6705
    let root = dir.path();
6706
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6707
    let long: String = (0..300)
6708
        .map(|i| format!("line {i} of a long file\n"))
6709
        .collect();
6710
    write(root, "long.txt", long.as_bytes());
6711
    write(root, "short.txt", b"short\n");
6712
    repo.commit("base", &[]).unwrap();
6713
    let (r1, _, _) = repo.checkpoint().unwrap();
6714
    let cp1 = crate::objects::Checkpoint::decode(
6715
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
6716
    )
6717
    .unwrap();
6718
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
6719
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
6720
6721
    // gc keeps the graph blob; fsck finds the checkpoint sound.
6722
    repo.gc(true).unwrap();
6723
    assert!(repo.store().has(&graphs1[0]));
6724
    let report = repo.fsck().unwrap();
6725
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
6726
6727
    // Loading through the checkpoint equals a full load.
6728
    write(root, "short.txt", b"short, edited\n");
6729
    repo.commit("edit the short file", &[]).unwrap();
6730
    let heads = repo.bookmark_heads().unwrap();
6731
    let fast = repo.load_state(&heads).unwrap();
6732
    let full = repo.load_state_full(&heads).unwrap();
6733
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
6734
6735
    // The next checkpoint shares the unchanged long file's graph.
6736
    let (r2, _, _) = repo.checkpoint().unwrap();
6737
    let cp2 = crate::objects::Checkpoint::decode(
6738
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
6739
    )
6740
    .unwrap();
6741
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
6742
6743
    // A shallow clone's bundle carries the graph blob with the checkpoint.
6744
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
6745
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
6746
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
6747
6748
    // A version 1 checkpoint written by an older oxy still loads.
6749
    let state = repo.load_state_full(&heads).unwrap();
6750
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
6751
    let cp_old = crate::objects::Checkpoint {
6752
        heads: cp2.heads.clone(),
6753
        count: cp2.count,
6754
        payload: old,
6755
    };
6756
    let r_old = repo
6757
        .store()
6758
        .put(ObjectType::Checkpoint, &cp_old.encode())
6759
        .unwrap();
6760
    repo.install_checkpoint("main", &r_old).unwrap();
6761
    assert_eq!(
6762
        repo.load_state(&heads).unwrap().checkpoint_payload(),
6763
        full.checkpoint_payload()
6764
    );
6765
    assert_eq!(repo.fsck().unwrap().errors(), 0);
6766
6767
    // A lost graph blob fails the load loudly rather than dropping the
6768
    // file, and fsck reports it (a fresh repository, objects still loose).
6769
    let dir2 = tempfile::tempdir().unwrap();
6770
    let root2 = dir2.path();
6771
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
6772
    write(root2, "long.txt", long.as_bytes());
6773
    repo2.commit("base", &[]).unwrap();
6774
    let (r, _, _) = repo2.checkpoint().unwrap();
6775
    let cp = crate::objects::Checkpoint::decode(
6776
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
6777
    )
6778
    .unwrap();
6779
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
6780
    repo2.store().remove_loose_for_test(&graph).unwrap();
6781
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
6782
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
6783
}
6784
6785
/// A new repository has not stored the user's identity yet (that happens
6786
/// at the first signed change); looking it up falls back to the key
6787
/// directory, and a file there that does not hash to the key is refused.
6788
#[test]
6789
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
6790
    hermetic();
6791
    let dir = tempfile::tempdir().unwrap();
6792
    let home = dir.path().join("home");
6793
    let mut first = Repo::init(&dir.path().join("a"))
6794
        .unwrap()
6795
        .with_home(home.clone());
6796
    let (key, _) = first
6797
        .create_identity("Ada", "[email protected]", IdentityScope::User)
6798
        .unwrap();
6799
    let fresh = Repo::init(&dir.path().join("b"))
6800
        .unwrap()
6801
        .with_home(home.clone());
6802
    assert!(!fresh.store().has(&key), "nothing stored yet");
6803
    let id = fresh.identity(&key).unwrap();
6804
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
6805
    // A key file that is not this identity is an error, not a wrong answer.
6806
    let keys = fresh.keys_dir.clone();
6807
    let (other, _) = first
6808
        .create_identity("Bob", "[email protected]", IdentityScope::User)
6809
        .unwrap();
6810
    fs::copy(
6811
        keys.join(format!("{}.identity", other.to_hex())),
6812
        keys.join(format!("{}.identity", key.to_hex())),
6813
    )
6814
    .unwrap();
6815
    assert!(fresh
6816
        .identity(&key)
6817
        .unwrap_err()
6818
        .to_string()
6819
        .contains("does not hold identity"));
6820
}
6821
6822
/// Status snapshots (spec §12.3): a text file whose stat matches the
6823
/// manifest, and whose base graph key is the one the manifest recorded it
6824
/// equal to, is neither read nor rendered; any edit, and any change to the
6825
/// file's graph in the base, brings it back.
6826
#[cfg(unix)]
6827
#[test]
6828
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
6829
    use std::os::unix::fs::PermissionsExt;
6830
    hermetic();
6831
    let dir = tempfile::tempdir().unwrap();
6832
    let root = dir.path();
6833
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6834
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
6835
        write(root, p, c.as_bytes());
6836
    }
6837
    repo.commit("base", &[]).unwrap();
6838
    let age = |p: &str| {
6839
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6840
        fs::File::options()
6841
            .write(true)
6842
            .open(root.join(p))
6843
            .unwrap()
6844
            .set_modified(old)
6845
            .unwrap();
6846
    };
6847
    let lock = |p: &str, mode: u32| {
6848
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
6849
    };
6850
    for p in ["a.txt", "b.txt", "d/c.txt"] {
6851
        age(p);
6852
    }
6853
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
6854
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6855
    assert!(
6856
        m.entries.values().all(|e| e.graph.is_some()),
6857
        "keys recorded"
6858
    );
6859
6860
    // Unreadable files prove they are not read; the status snapshot does
6861
    // not render them either, and its base lacks their graphs.
6862
    lock("a.txt", 0o000);
6863
    lock("b.txt", 0o000);
6864
    let snap = repo.snapshot_status("status").unwrap();
6865
    assert!(!snap.changed && snap.statuses.is_empty());
6866
    assert_eq!(
6867
        snap.base_snapshot
6868
            .unrendered
6869
            .iter()
6870
            .cloned()
6871
            .collect::<Vec<_>>(),
6872
        vec!["a.txt", "b.txt", "d/c.txt"]
6873
    );
6874
    assert!(!snap.base.is_full());
6875
    assert!(!snap.base_snapshot.is_conflicted());
6876
    // A full snapshot does not read them either, but renders everything.
6877
    let full = repo.snapshot("status").unwrap();
6878
    assert!(full.statuses.is_empty() && full.base.is_full());
6879
    assert!(full.base_snapshot.unrendered.is_empty());
6880
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
6881
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
6882
6883
    // An edit is seen; the file is rendered, the others still are not.
6884
    write(root, "d/c.txt", b"sea edited\n");
6885
    let snap = repo.snapshot_status("status").unwrap();
6886
    assert_eq!(
6887
        statuses(&snap),
6888
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
6889
    );
6890
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
6891
    // So is a mode change of an unread file.
6892
    lock("b.txt", 0o100);
6893
    assert_eq!(
6894
        statuses(&repo.snapshot_status("status").unwrap()),
6895
        vec![
6896
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
6897
            ("d/c.txt".to_string(), ChangeStatus::Modified)
6898
        ]
6899
    );
6900
    lock("b.txt", 0o000);
6901
6902
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
6903
    // stays unread, c.txt is read once and then skipped too.
6904
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
6905
        .unwrap();
6906
    age("d/c.txt");
6907
    let snap = repo.snapshot_status("status").unwrap();
6908
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
6909
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
6910
    lock("d/c.txt", 0o000);
6911
    let snap = repo.snapshot_status("status").unwrap();
6912
    assert!(snap.statuses.is_empty());
6913
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
6914
    for p in ["a.txt", "b.txt", "d/c.txt"] {
6915
        lock(p, 0o644);
6916
    }
6917
}
6918
6919
/// Attributes decide how a file compares with the base, so a changed
6920
/// `.oxyattributes` makes every text file be compared again.
6921
#[cfg(unix)]
6922
#[test]
6923
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
6924
    hermetic();
6925
    let dir = tempfile::tempdir().unwrap();
6926
    let root = dir.path();
6927
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6928
    write(root, "a.txt", b"crlf\r\n");
6929
    repo.commit("base", &[]).unwrap();
6930
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6931
    fs::File::options()
6932
        .write(true)
6933
        .open(root.join("a.txt"))
6934
        .unwrap()
6935
        .set_modified(old)
6936
        .unwrap();
6937
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6938
    assert!(repo
6939
        .snapshot_status("status")
6940
        .unwrap()
6941
        .base_snapshot
6942
        .unrendered
6943
        .contains("a.txt"));
6944
    // With eol=lf, a.txt as stored no longer equals the base.
6945
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
6946
    let snap = repo.snapshot_status("status").unwrap();
6947
    assert_eq!(
6948
        statuses(&snap),
6949
        vec![
6950
            (".oxyattributes".to_string(), ChangeStatus::Added),
6951
            ("a.txt".to_string(), ChangeStatus::Modified)
6952
        ]
6953
    );
6954
}
6955
6956
/// Bookmarks with `/` in their names: pushing records their
6957
/// attestations, and checkpoints are kept for them, beside `feature`
6958
/// itself.
6959
#[test]
6960
fn bookmarks_with_slashes_push_and_checkpoint() {
6961
    hermetic();
6962
    let dir = tempfile::tempdir().unwrap();
6963
    let root = dir.path();
6964
    let origin = Repo::init(&root.join("origin")).unwrap();
6965
    let url = root.join("origin").to_string_lossy().to_string();
6966
    let mut repo = Repo::clone(&url, &root.join("r"))
6967
        .unwrap()
6968
        .with_home(root.join("home"));
6969
    // With an identity, pushes carry reference attestations: the case
6970
    // that failed, since the attestation is a file named after the bookmark.
6971
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6972
        .unwrap();
6973
    let r = root.join("r");
6974
    write(&r, "a.txt", b"a\n");
6975
    let h_a = repo.commit("a", &[]).unwrap();
6976
    assert!(repo.push("origin", false).unwrap()[0].ok);
6977
    origin.refresh().unwrap();
6978
    repo.bookmark_create("feature", None).unwrap();
6979
    repo.bookmark_create("feature/x", None).unwrap();
6980
    repo.bookmark_switch("feature/x", false).unwrap();
6981
    write(&r, "b.txt", b"b\n");
6982
    let h_b = repo.commit("b", &[]).unwrap();
6983
    for name in ["feature", "feature/x"] {
6984
        let res = repo.push_bookmark("origin", name, false).unwrap();
6985
        origin.refresh().unwrap();
6986
        assert!(res[0].ok, "{name}: {res:?}");
6987
    }
6988
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
6989
    assert_eq!(
6990
        origin.resolve_heads("feature/x").unwrap(),
6991
        repo.resolve_heads("feature/x").unwrap()
6992
    );
6993
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
6994
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
6995
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
6996
6997
    // A checkpoint of feature/x is found again when loading its state.
6998
    let (cp, _, _) = repo.checkpoint().unwrap();
6999
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
7000
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
7001
    let heads = repo.resolve_heads("feature/x").unwrap();
7002
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
7003
}
7004
7005
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
7006
/// never the remote's own bookmark, and a bookmark created again later is
7007
/// accepted although the deletion's attestation stays the latest.
7008
#[test]
7009
fn bookmarks_are_deleted_on_a_remote() {
7010
    hermetic();
7011
    let dir = tempfile::tempdir().unwrap();
7012
    let root = dir.path();
7013
    let origin = Repo::init(&root.join("origin")).unwrap();
7014
    let url = root.join("origin").to_string_lossy().to_string();
7015
    let mut repo = Repo::clone(&url, &root.join("r"))
7016
        .unwrap()
7017
        .with_home(root.join("home"));
7018
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
7019
        .unwrap();
7020
    let r = root.join("r");
7021
    write(&r, "a.txt", b"a\n");
7022
    repo.commit("a", &[]).unwrap();
7023
    assert!(repo.push("origin", false).unwrap()[0].ok);
7024
    origin.refresh().unwrap();
7025
    repo.bookmark_create("feature/x", None).unwrap();
7026
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
7027
    origin.refresh().unwrap();
7028
    assert!(origin.resolve_heads("feature/x").is_ok());
7029
7030
    let res = repo.push_delete("origin", "feature/x").unwrap();
7031
    origin.refresh().unwrap();
7032
    assert!(res[0].ok, "{res:?}");
7033
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
7034
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
7035
    assert!(
7036
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
7037
        "the deletion is attested"
7038
    );
7039
    assert!(
7040
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
7041
        "the local bookmark stays"
7042
    );
7043
    assert!(!repo
7044
        .view()
7045
        .unwrap()
7046
        .remotes
7047
        .get("origin")
7048
        .is_some_and(|m| m.contains_key("feature/x")));
7049
7050
    // Pushing it again creates it again, past the deletion's serial.
7051
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
7052
    origin.refresh().unwrap();
7053
    assert!(res[0].ok, "{res:?}");
7054
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
7055
7056
    // Nothing to delete, and never the remote's own bookmark.
7057
    assert!(repo.push_delete("origin", "nope").is_err());
7058
    let res = repo.push_delete("origin", "main").unwrap();
7059
    origin.refresh().unwrap();
7060
    assert!(
7061
        !res[0].ok && res[0].reason.contains("default bookmark"),
7062
        "{res:?}"
7063
    );
7064
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
7065
}
7066
7067
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
7068
/// when the target has the same versions of the files it touches, and is
7069
/// refused, untouched, when it has others.
7070
#[test]
7071
fn switching_bookmarks_carries_uncommitted_work() {
7072
    hermetic();
7073
    let dir = tempfile::tempdir().unwrap();
7074
    let root = dir.path();
7075
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7076
    write(root, "a.txt", b"a\n");
7077
    write(root, "b.txt", b"b\n");
7078
    write(root, "gone.txt", b"gone\n");
7079
    repo.commit("base", &[]).unwrap();
7080
    repo.bookmark_create("feature", None).unwrap();
7081
    // Started on main, belongs on feature: edit, add, remove.
7082
    write(root, "a.txt", b"a\nmore\n");
7083
    write(root, "new.txt", b"new\n");
7084
    fs::remove_file(root.join("gone.txt")).unwrap();
7085
    let (report, carried) = repo.bookmark_switch_carry("feature").unwrap();
7086
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
7087
    // oxygen#120: the new file was carried, not removed.
7088
    assert_eq!(
7089
        (report.removed, report.removed_paths.len()),
7090
        (0, 0),
7091
        "{report:?}"
7092
    );
7093
    assert_eq!(repo.config.bookmark, "feature");
7094
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
7095
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
7096
    assert!(!root.join("gone.txt").exists());
7097
    let snap = repo.snapshot("status").unwrap();
7098
    assert_eq!(
7099
        statuses(&snap),
7100
        vec![
7101
            ("a.txt".to_string(), ChangeStatus::Modified),
7102
            ("gone.txt".to_string(), ChangeStatus::Removed),
7103
            ("new.txt".to_string(), ChangeStatus::Added)
7104
        ]
7105
    );
7106
    repo.commit("the work", &[]).unwrap();
7107
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
7108
7109
    // main moves b.txt on; work on feature touching b.txt cannot follow.
7110
    repo.bookmark_switch("main", false).unwrap();
7111
    write(root, "b.txt", b"b on main\n");
7112
    repo.commit("b on main", &[]).unwrap();
7113
    repo.bookmark_switch("feature", false).unwrap();
7114
    write(root, "b.txt", b"b edited\n");
7115
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
7116
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
7117
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
7118
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
7119
}
7120
7121
/// Merging and checking out (feedback 3): a working copy without changes
7122
/// follows a merge whichever state it sat on; a refused checkout names
7123
/// what is in the way; `checkout --carry` takes the work along.
7124
#[test]
7125
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
7126
    hermetic();
7127
    let dir = tempfile::tempdir().unwrap();
7128
    let root = dir.path();
7129
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7130
    write(root, "a.txt", b"a\n");
7131
    let h1 = repo.commit("a", &[]).unwrap();
7132
    write(root, "b.txt", b"b\n");
7133
    repo.commit("b", &[]).unwrap();
7134
    repo.bookmark_create("feature", None).unwrap();
7135
    repo.bookmark_switch("feature", false).unwrap();
7136
    write(root, "c.txt", b"c\n");
7137
    repo.commit("c on feature", &[]).unwrap();
7138
    repo.bookmark_switch("main", false).unwrap();
7139
    // The working copy sits on an older state than main's heads.
7140
    repo.checkout(&[h1], false, "checkout").unwrap();
7141
    assert!(!root.join("b.txt").exists());
7142
    let m = repo.merge("feature").unwrap();
7143
    assert!(m.checked_out, "a clean working copy follows the merge");
7144
    for f in ["a.txt", "b.txt", "c.txt"] {
7145
        assert!(root.join(f).exists(), "{f}");
7146
    }
7147
7148
    // A refusal says which paths are in the way and what to do.
7149
    fs::remove_file(root.join("b.txt")).unwrap();
7150
    write(root, "a.txt", b"a edited\n");
7151
    let err = repo
7152
        .checkout(&[h1], false, "checkout")
7153
        .unwrap_err()
7154
        .to_string();
7155
    assert!(
7156
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
7157
        "{err}"
7158
    );
7159
    // --carry takes them along: h1 has a.txt as the base has it, and the
7160
    // removed b.txt is already as h1 has it (none), so that is no conflict
7161
    // either (oxygen#100).
7162
    let (_, carried) = repo
7163
        .checkout_carry(&[h1], "the first change", "checkout")
7164
        .unwrap();
7165
    assert_eq!(carried, vec!["a.txt"]);
7166
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
7167
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
7168
}
7169
7170
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
7171
/// user identity not stored in a new repository yet is fine while its
7172
/// secret key is there; an added subrepo is listed as not committed yet.
7173
#[test]
7174
fn a_new_repository_is_healthy_before_its_first_commit() {
7175
    hermetic();
7176
    let dir = tempfile::tempdir().unwrap();
7177
    let root = dir.path();
7178
    let home = root.join("home");
7179
    let mut first = Repo::init(&root.join("first"))
7180
        .unwrap()
7181
        .with_home(home.clone());
7182
    let (key, _) = first
7183
        .create_identity("Ada", "[email protected]", IdentityScope::User)
7184
        .unwrap();
7185
    let repo = Repo::init(&root.join("second"))
7186
        .unwrap()
7187
        .with_home(home.clone());
7188
    // Only the secret key: no identity object anywhere this repository sees.
7189
    let keys = repo.keys_dir.clone();
7190
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
7191
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
7192
    let r = repo.doctor(true);
7193
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
7194
    assert_eq!(id.health, Health::Ok, "{}", id.message);
7195
    assert!(id.message.contains("first signed change"), "{}", id.message);
7196
7197
    // A subrepo added and not committed yet is listed, pinned where it is.
7198
    let lib = root.join("lib");
7199
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
7200
    write(&lib, "x.txt", b"x\n");
7201
    l.commit("x", &[]).unwrap();
7202
    let second = root.join("second");
7203
    write(&second, "a.txt", b"a\n");
7204
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
7205
        .unwrap();
7206
    let subs = repo.subrepos().unwrap();
7207
    assert_eq!(subs.len(), 1);
7208
    assert_eq!(
7209
        (subs[0].path.as_str(), subs[0].committed),
7210
        ("deps/lib", false)
7211
    );
7212
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
7213
    repo.commit("add lib", &[]).unwrap();
7214
    let subs = repo.subrepos().unwrap();
7215
    assert!(subs[0].committed, "committed now");
7216
}
7217
7218
/// Commit, diff, hunks and discard use the partial snapshot: a file
7219
/// unchanged since the manifest is neither read nor rendered, and showing
7220
/// a change renders only what it edits, the same as from a full base.
7221
#[cfg(unix)]
7222
#[test]
7223
fn commits_and_diffs_leave_unchanged_files_alone() {
7224
    use std::os::unix::fs::PermissionsExt;
7225
    hermetic();
7226
    let dir = tempfile::tempdir().unwrap();
7227
    let root = dir.path();
7228
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
7229
    write(root, "big.txt", b"lots\nof\nlines\n");
7230
    write(root, "a.txt", b"one\ntwo\n");
7231
    repo.commit("base", &[]).unwrap();
7232
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
7233
    for f in ["big.txt", "a.txt"] {
7234
        fs::File::options()
7235
            .write(true)
7236
            .open(root.join(f))
7237
            .unwrap()
7238
            .set_modified(old)
7239
            .unwrap();
7240
    }
7241
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
7242
    // big.txt cannot be read at all from here on.
7243
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
7244
7245
    write(root, "a.txt", b"one\nTWO\nthree\n");
7246
    let diff = repo.diff_files(None).unwrap();
7247
    assert_eq!(
7248
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
7249
        ["a.txt"]
7250
    );
7251
    let (_, hunks) = repo.hunks().unwrap();
7252
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
7253
    let h = repo.commit("edit a", &[]).unwrap();
7254
7255
    // Showing the change needs only a.txt's graph, and renders as a full base does.
7256
    let c = repo.store().get_change(&h).unwrap();
7257
    let full = repo.load_state(&c.deps).unwrap();
7258
    let want = render_change(&c, &full, &full.materialize());
7259
    assert_eq!(repo.describe_change(&h).unwrap(), want);
7260
    let (base, snap) = repo.change_base(&c).unwrap();
7261
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
7262
7263
    // Discarding works the same way.
7264
    write(root, "a.txt", b"scratch\n");
7265
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
7266
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
7267
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
7268
}
7269
7270
/// A replace conflict (spec §9.3) is settled by a change that writes one
7271
/// candidate, or new bytes, at the path when the caller names it; a plain
7272
/// snapshot of a checkout never settles it on its own.
7273
#[test]
7274
fn replace_conflicts_are_settled_when_asked() {
7275
    hermetic();
7276
    let dir = tempfile::tempdir().unwrap();
7277
    let root = dir.path();
7278
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7279
    let blob = |n: u8| {
7280
        let mut v = vec![0u8; 64];
7281
        v[1] = n;
7282
        v
7283
    };
7284
    write(root, "img.bin", &blob(1));
7285
    repo.commit("add img", &[]).unwrap();
7286
    repo.bookmark_create("other", None).unwrap();
7287
    write(root, "img.bin", &blob(2));
7288
    repo.commit("img two", &[]).unwrap();
7289
    repo.bookmark_switch("other", false).unwrap();
7290
    write(root, "img.bin", &blob(3));
7291
    repo.commit("img three", &[]).unwrap();
7292
    repo.bookmark_switch("main", false).unwrap();
7293
    repo.merge("other").unwrap();
7294
    let heads = repo.bookmark_heads().unwrap();
7295
    let merged = repo.load_state(&heads).unwrap().materialize();
7296
    assert!(
7297
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
7298
        "a replace conflict"
7299
    );
7300
    // A snapshot of the checkout records nothing.
7301
    assert!(repo
7302
        .snapshot("status")
7303
        .unwrap()
7304
        .statuses
7305
        .iter()
7306
        .all(|s| s.path != "img.bin"));
7307
7308
    // Keeping candidate 3 settles it.
7309
    let author = repo.author();
7310
    let edits = [FileEdit {
7311
        path: "img.bin".into(),
7312
        content: Some(blob(3)),
7313
    }];
7314
    let c = repo
7315
        .build_change(&heads, &edits, "keep three", author)
7316
        .unwrap();
7317
    assert_eq!(c.kind, ChangeKind::Resolution);
7318
    let mut st = repo.load_state(&heads).unwrap();
7319
    for d in &c.deps {
7320
        assert!(st.contains(d));
7321
    }
7322
    assert!(
7323
        heads.iter().all(|h| c.deps.contains(h)),
7324
        "depends on both contributors"
7325
    );
7326
    st.add(c).unwrap();
7327
    let after = st.materialize();
7328
    assert!(!after.is_conflicted());
7329
    assert_eq!(
7330
        after.files["img.bin"].content,
7331
        FileContent::Opaque {
7332
            blobs: vec![Repo::blob_ref(&blob(3))]
7333
        }
7334
    );
7335
7336
    // New bytes settle it too.
7337
    let edits = [FileEdit {
7338
        path: "img.bin".into(),
7339
        content: Some(blob(9)),
7340
    }];
7341
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
7342
    let mut st = repo.load_state(&heads).unwrap();
7343
    st.add(c).unwrap();
7344
    assert_eq!(
7345
        st.materialize().files["img.bin"].content,
7346
        FileContent::Opaque {
7347
            blobs: vec![Repo::blob_ref(&blob(9))]
7348
        }
7349
    );
7350
}
7351
7352
/// The history of a range of lines (spec §27): the changes that wrote
7353
/// or deleted its atoms, or deleted atoms from between them; edits outside
7354
/// the range and changes the range's lines survived are not in it.
7355
#[test]
7356
fn line_ranges_have_exact_histories() {
7357
    hermetic();
7358
    let dir = tempfile::tempdir().unwrap();
7359
    let root = dir.path();
7360
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
7361
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
7362
    let base = repo.commit("add f", &[]).unwrap();
7363
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
7364
    let outside = repo.commit("change the import", &[]).unwrap();
7365
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
7366
    let inside = repo.commit("edit a line of a", &[]).unwrap();
7367
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
7368
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
7369
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
7370
    let after = repo.commit("add b after a", &[]).unwrap();
7371
    let heads = repo.bookmark_heads().unwrap();
7372
7373
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
7374
    let hist: Vec<ChangeHash> = repo
7375
        .line_history(&heads, "f.rs", 2, 4)
7376
        .unwrap()
7377
        .iter()
7378
        .map(|e| e.hash)
7379
        .collect();
7380
    for (h, what) in [
7381
        (base, "wrote it"),
7382
        (inside, "edited a line"),
7383
        (deleted, "deleted a line from inside"),
7384
    ] {
7385
        assert!(hist.contains(&h), "{what}");
7386
    }
7387
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
7388
        assert!(!hist.contains(&h), "{what}");
7389
    }
7390
    assert_eq!(hist[0], deleted, "newest first");
7391
    // One line: only what touched it.
7392
    let one: Vec<ChangeHash> = repo
7393
        .line_history(&heads, "f.rs", 1, 1)
7394
        .unwrap()
7395
        .iter()
7396
        .map(|e| e.hash)
7397
        .collect();
7398
    assert!(one.contains(&outside) && !one.contains(&inside));
7399
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
7400
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
7401
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
7402
}
7403
7404
#[test]
7405
fn receipts_are_kept_with_their_state_and_verified() {
7406
    use crate::receipt::{Receipt, SignedReceipt};
7407
    hermetic();
7408
    let dir = tempfile::tempdir().unwrap();
7409
    let root = dir.path();
7410
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
7411
    write(root, "a.txt", b"1\n");
7412
    repo.commit("A", &[]).unwrap();
7413
    let heads = repo.bookmark_heads().unwrap();
7414
    let state = repo
7415
        .store()
7416
        .put_state(&StateObject::new(heads.clone()))
7417
        .unwrap();
7418
    let out = repo.store_blob(b"built\n").unwrap();
7419
    let receipt = Receipt {
7420
        job_name: "build".into(),
7421
        pipeline_hash: ObjectRef([1; 32]),
7422
        scope_tree_hash: ObjectRef([2; 32]),
7423
        inputs: vec![],
7424
        environment: ObjectRef([3; 32]),
7425
        outputs: vec![out],
7426
        exit_code: 0,
7427
        duration_ms: 42,
7428
    };
7429
    let sk = SecretKey::generate();
7430
    let runner = sk.identity("earth-1", "runner@earth", 1);
7431
    let sr = SignedReceipt::sign(
7432
        receipt.clone(),
7433
        repo.id().unwrap(),
7434
        state,
7435
        "demo#1",
7436
        &runner,
7437
        &sk,
7438
    );
7439
7440
    let r = repo.add_receipt(&sr).unwrap();
7441
    let found = repo.receipts(&heads).unwrap();
7442
    assert_eq!(found.len(), 1);
7443
    assert_eq!(found[0].attest, r);
7444
    assert_eq!(found[0].signed, sr);
7445
    assert!(found[0].problem.is_none() && !found[0].revoked);
7446
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
7447
7448
    // Another repository's receipt, or a forged one, is refused.
7449
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
7450
    assert!(repo
7451
        .add_receipt(&elsewhere)
7452
        .unwrap_err()
7453
        .to_string()
7454
        .contains("another repository"));
7455
    let mut forged = sr.clone();
7456
    forged.receipt.exit_code = 1;
7457
    assert!(repo
7458
        .add_receipt(&forged)
7459
        .unwrap_err()
7460
        .to_string()
7461
        .contains("does not verify"));
7462
7463
    // A receipt signed by a short-lived key keeps its certificate and the
7464
    // issuer's identity, and reads back with them (oxygenhub#241).
7465
    let hub_sk = SecretKey::generate();
7466
    let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
7467
    let job_sk = SecretKey::generate();
7468
    let job = job_sk.identity("job 2 test", "[email protected]", 1);
7469
    let mut test_receipt = receipt.clone();
7470
    test_receipt.job_name = "test".into();
7471
    let plain = SignedReceipt::sign(
7472
        test_receipt,
7473
        repo.id().unwrap(),
7474
        state,
7475
        "demo#2",
7476
        &job,
7477
        &job_sk,
7478
    );
7479
    let now = plain.attest.hlc.wall_ms;
7480
    let cert = crate::cert::SignedCertificate::sign(
7481
        crate::cert::Certificate {
7482
            key: job.clone(),
7483
            issuer: hub.hash(),
7484
            subject: "repo:andy/demo:bookmark:main".into(),
7485
            claims: vec![],
7486
            scope: crate::identity::Scope::SEAL,
7487
            not_before: now - 1_000,
7488
            expires: now + 600_000,
7489
            grant: None,
7490
        },
7491
        &hub,
7492
        &hub_sk,
7493
    );
7494
    let certified = plain.with_certificate(cert, hub.clone());
7495
    repo.add_receipt(&certified).unwrap();
7496
    let found = repo.receipts(&heads).unwrap();
7497
    let got = found
7498
        .iter()
7499
        .find(|i| i.signed.receipt.job_name == "test")
7500
        .unwrap();
7501
    assert_eq!(got.signed, certified);
7502
    assert!(got.problem.is_none(), "{:?}", got.problem);
7503
7504
    // gc keeps the receipts, their runners, the certificate and its issuer,
7505
    // and the output while the state lives.
7506
    repo.gc(true).unwrap();
7507
    let found = repo.receipts(&heads).unwrap();
7508
    assert_eq!(found.len(), 2);
7509
    let got = found
7510
        .iter()
7511
        .find(|i| i.signed.receipt.job_name == "test")
7512
        .unwrap();
7513
    assert_eq!(got.signed, certified, "the certificate survives gc");
7514
    assert!(got.problem.is_none());
7515
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
7516
    assert!(repo.fsck().unwrap().problems.is_empty());
7517
}
7518
7519
#[test]
7520
fn approvals_are_kept_with_their_state_and_survive_gc() {
7521
    hermetic();
7522
    let dir = tempfile::tempdir().unwrap();
7523
    let root = dir.path();
7524
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
7525
    write(root, "a.txt", b"1\n");
7526
    repo.commit("A", &[]).unwrap();
7527
    let heads = repo.bookmark_heads().unwrap();
7528
    let state = repo.store().put_state(&StateObject::new(heads)).unwrap();
7529
    let plan = repo.store_blob(b"the reviewed plan\n").unwrap();
7530
    let sk = SecretKey::generate();
7531
    let andy = sk.identity("Andy", "[email protected]", 1);
7532
    let statement = crate::approval::Statement {
7533
        repo: repo.id().unwrap(),
7534
        run: "https://hub.example/andy/infra/flow/8".into(),
7535
        job: "apply".into(),
7536
        job_hash: ObjectRef([1; 32]),
7537
        state,
7538
        inputs: vec![plan],
7539
        environment: "prod".into(),
7540
        approve: true,
7541
    };
7542
    let sa = crate::approval::SignedApproval::sign(&statement, &andy, &sk);
7543
    let r = repo.add_approval(&sa).unwrap();
7544
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
7545
    // Another repository's approval, or a changed one, is refused.
7546
    let elsewhere = crate::approval::SignedApproval::sign(
7547
        &crate::approval::Statement {
7548
            repo: [0; 16],
7549
            ..statement.clone()
7550
        },
7551
        &andy,
7552
        &sk,
7553
    );
7554
    assert!(repo
7555
        .add_approval(&elsewhere)
7556
        .unwrap_err()
7557
        .to_string()
7558
        .contains("another repository"));
7559
    let mut forged = sa.clone();
7560
    if let AttestBody::Approval { environment, .. } = &mut forged.attest.body {
7561
        *environment = "dev".into();
7562
    }
7563
    assert!(repo
7564
        .add_approval(&forged)
7565
        .unwrap_err()
7566
        .to_string()
7567
        .contains("does not verify"));
7568
    // gc keeps it, its signature and its signer while the state lives.
7569
    repo.gc(true).unwrap();
7570
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
7571
    assert_eq!(repo.store().get_attest(&r).unwrap(), sa.attest);
7572
    assert_eq!(repo.store().signatures(&r).unwrap(), sa.sigs);
7573
    assert!(repo.fsck().unwrap().problems.is_empty());
7574
}
7575
7576
#[test]
7577
fn status_leaves_an_unchanged_manifest_alone() {
7578
    hermetic();
7579
    let dir = tempfile::tempdir().unwrap();
7580
    let root = dir.path();
7581
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
7582
    write(root, "a.txt", b"1\n");
7583
    write(root, "b.txt", b"2\n");
7584
    repo.commit("A", &[]).unwrap();
7585
    // Files last touched well outside the racy window.
7586
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7587
    for f in ["a.txt", "b.txt"] {
7588
        fs::File::options()
7589
            .write(true)
7590
            .open(root.join(f))
7591
            .unwrap()
7592
            .set_modified(old)
7593
            .unwrap();
7594
    }
7595
    repo.snapshot_status("status").unwrap();
7596
    let path = repo.manifest_path();
7597
    let first = fs::read(&path).unwrap();
7598
    repo.snapshot_status("status").unwrap();
7599
    assert_eq!(
7600
        fs::read(&path).unwrap(),
7601
        first,
7602
        "an unchanged tree does not rewrite the manifest"
7603
    );
7604
    // A change rewrites it.
7605
    write(root, "a.txt", b"1\n2\n");
7606
    repo.snapshot_status("status").unwrap();
7607
    assert_ne!(fs::read(&path).unwrap(), first);
7608
}
7609
7610
#[test]
7611
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
7612
    hermetic();
7613
    let dir = tempfile::tempdir().unwrap();
7614
    let root = dir.path();
7615
    let origin_path = root.join("origin");
7616
    Repo::init(&origin_path).unwrap();
7617
    let origin_url = origin_path.to_string_lossy().to_string();
7618
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
7619
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
7620
    write(&root.join("a"), "big.txt", big.as_bytes());
7621
    write(&root.join("a"), "small.txt", b"small\n");
7622
    let h1 = a.commit("large", &[]).unwrap();
7623
    let (_, body) = a.store().get(&h1).unwrap();
7624
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
7625
    assert!(a.push("origin", false).unwrap()[0].ok);
7626
7627
    // A clone reads the text from the blobs that came with the change.
7628
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
7629
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
7630
    // An edit in the middle of the stored insert is an ordinary change.
7631
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
7632
    write(&root.join("b"), "big.txt", edited.as_bytes());
7633
    let h2 = b.commit("edit", &[]).unwrap();
7634
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
7635
    assert!(b.push("origin", false).unwrap()[0].ok);
7636
    assert!(a.pull("origin").unwrap().checked_out);
7637
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
7638
    assert_eq!(
7639
        a.fsck().unwrap().errors(),
7640
        0,
7641
        "{:?}",
7642
        a.fsck().unwrap().problems
7643
    );
7644
7645
    // With zero retention gc keeps the text blobs of every kept change.
7646
    let mut a = Repo::open(&root.join("a")).unwrap();
7647
    a.config.set("core.op-retention", "0").unwrap();
7648
    a.save_config().unwrap();
7649
    let a = Repo::open(&root.join("a")).unwrap();
7650
    a.gc(true).unwrap();
7651
    let a = Repo::open(&root.join("a")).unwrap();
7652
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
7653
    assert_eq!(
7654
        a.fsck().unwrap().errors(),
7655
        0,
7656
        "{:?}",
7657
        a.fsck().unwrap().problems
7658
    );
7659
    // And a clone of the packed repository reads them from its packs.
7660
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
7661
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
7662
    drop(c);
7663
}
7664
7665
#[test]
7666
fn operations_that_both_replace_a_working_copy_are_not_merged() {
7667
    hermetic();
7668
    let dir = tempfile::tempdir().unwrap();
7669
    let root = dir.path();
7670
    let repo = Repo::init(root).unwrap();
7671
    write(root, "a.txt", b"a\n");
7672
    let a = repo.commit("a", &[]).unwrap();
7673
    write(root, "b.txt", b"b\n");
7674
    repo.commit("b", &[]).unwrap();
7675
    let (x, op) = repo.head_op().unwrap();
7676
    let ws = *op.view.workspaces.keys().next().unwrap();
7677
    let mut one = op.view.clone();
7678
    one.workspaces.insert(ws, a);
7679
    let mut two = op.view.clone();
7680
    two.workspaces.insert(ws, ObjectRef([7; 32]));
7681
    let first = repo.record_op(&[x], "one", one).unwrap();
7682
    let e = repo.record_op(&[x], "two", two).unwrap_err();
7683
    assert!(
7684
        e.to_string()
7685
            .contains("changed this working copy at the same time"),
7686
        "{e}"
7687
    );
7688
    assert_eq!(
7689
        repo.head_op().unwrap().0,
7690
        first,
7691
        "the second is not recorded"
7692
    );
7693
}
7694
7695
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
7696
/// rewrote the working copy recorded the half-written files as edits, and
7697
/// its view replaced the switch's.
7698
#[test]
7699
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
7700
    hermetic();
7701
    let dir = tempfile::tempdir().unwrap();
7702
    let root = dir.path().to_path_buf();
7703
    let mut repo = Repo::init(&root).unwrap();
7704
    write(&root, "keep.txt", b"keep\n");
7705
    repo.commit("base", &[]).unwrap();
7706
    repo.bookmark_create("small", None).unwrap();
7707
    for i in 0..300 {
7708
        write(
7709
            &root,
7710
            &format!("many/f{i}.txt"),
7711
            format!("file {i}\n").as_bytes(),
7712
        );
7713
    }
7714
    repo.commit("many", &[]).unwrap();
7715
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
7716
    let watcher = {
7717
        let (root, stop) = (root.clone(), stop.clone());
7718
        std::thread::spawn(move || {
7719
            let r = Repo::open(&root).unwrap();
7720
            let mut ran = 0;
7721
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
7722
                if r.snapshot_status("oxy status").is_ok() {
7723
                    ran += 1;
7724
                }
7725
            }
7726
            ran
7727
        })
7728
    };
7729
    for i in 0..20 {
7730
        let to = if i % 2 == 0 { "small" } else { "main" };
7731
        repo.bookmark_switch(to, false).unwrap();
7732
    }
7733
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
7734
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
7735
    // Back on main, clean, with every file where main has it.
7736
    let repo = Repo::open(&root).unwrap();
7737
    let s = repo.snapshot_status("oxy status").unwrap();
7738
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
7739
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
7740
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
7741
    assert!(root.join("many/f299.txt").exists());
7742
}
7743
7744
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
7745
/// put a subrepo that was ahead of its pin back at the pin and moved the
7746
/// subrepo's own bookmark backwards.
7747
#[test]
7748
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
7749
    hermetic();
7750
    let dir = tempfile::tempdir().unwrap();
7751
    let root = dir.path();
7752
    Repo::init(&root.join("lib-origin")).unwrap();
7753
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7754
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
7755
    write(&root.join("lib"), "lib.txt", b"v1\n");
7756
    lib.commit("lib v1", &[]).unwrap();
7757
    assert!(lib.push("origin", false).unwrap()[0].ok);
7758
7759
    let app_dir = root.join("app");
7760
    let mut app = Repo::init(&app_dir).unwrap();
7761
    write(&app_dir, "main.txt", b"app\n");
7762
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7763
    app.commit("app with lib", &[]).unwrap();
7764
    app.bookmark_create("feature", None).unwrap();
7765
7766
    // New work in the subrepo, not yet pinned by the parent.
7767
    let nested_dir = app_dir.join("libs/lib");
7768
    let nested = Repo::open(&nested_dir).unwrap();
7769
    write(&nested_dir, "new.txt", b"new\n");
7770
    let l2 = nested.commit("lib: new file", &[]).unwrap();
7771
    drop(nested);
7772
7773
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
7774
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
7775
    let nested = Repo::open(&nested_dir).unwrap();
7776
    assert!(
7777
        nested.bookmark_heads().unwrap().contains(&l2),
7778
        "its bookmark kept its work"
7779
    );
7780
    assert!(nested_dir.join("new.txt").exists(), "and its files");
7781
    let s = app.snapshot("status").unwrap();
7782
    assert_eq!(
7783
        statuses(&s),
7784
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
7785
    );
7786
}
7787
7788
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
7789
/// moving `main` to a change this clone had pushed on another bookmark,
7790
/// the first `pull` said "Already up to date" while `main` was behind.
7791
#[test]
7792
fn pull_takes_a_remote_move_to_changes_already_here() {
7793
    hermetic();
7794
    let dir = tempfile::tempdir().unwrap();
7795
    let root = dir.path();
7796
    let origin_path = root.join("origin");
7797
    let origin = Repo::init(&origin_path).unwrap();
7798
    let url = origin_path.to_string_lossy().to_string();
7799
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
7800
    write(&root.join("b"), "base.txt", b"base\n");
7801
    b.commit("base", &[]).unwrap();
7802
    assert!(b.push("origin", false).unwrap()[0].ok);
7803
    origin.refresh().unwrap();
7804
7805
    // A feature bookmark with one change, pushed.
7806
    b.bookmark_create("feat", None).unwrap();
7807
    b.bookmark_switch("feat", false).unwrap();
7808
    write(&root.join("b"), "x.txt", b"x\n");
7809
    let x = b.commit("x", &[]).unwrap();
7810
    assert!(b.push("origin", false).unwrap()[0].ok);
7811
    origin.refresh().unwrap();
7812
    b.bookmark_switch("main", false).unwrap();
7813
7814
    // The remote lands it: its main moves to the feature's state.
7815
    let feat = origin
7816
        .store()
7817
        .get_state(&origin.view().unwrap().bookmarks["feat"])
7818
        .unwrap()
7819
        .heads;
7820
    origin.bookmark_set("main", &feat).unwrap();
7821
7822
    let r = b.pull("origin").unwrap();
7823
    assert!(r.changed, "{r:?}");
7824
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
7825
    let main = b
7826
        .bookmarks()
7827
        .unwrap()
7828
        .into_iter()
7829
        .find(|m| m.name == "main")
7830
        .unwrap();
7831
    assert_eq!(main.behind, Some(0), "{main:?}");
7832
}
7833
7834
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
7835
/// to one only the remote has makes a local bookmark from it; a pull moves
7836
/// every local bookmark the remote has too; a clone checks out the remote's
7837
/// default bookmark.
7838
#[test]
7839
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
7840
    hermetic();
7841
    let dir = tempfile::tempdir().unwrap();
7842
    let root = dir.path();
7843
    let origin_path = root.join("origin");
7844
    let mut origin = Repo::init(&origin_path).unwrap();
7845
    let url = origin_path.to_string_lossy().to_string();
7846
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
7847
    write(&root.join("a"), "base.txt", b"base\n");
7848
    a.commit("base", &[]).unwrap();
7849
    assert!(a.push("origin", false).unwrap()[0].ok);
7850
    a.bookmark_create("develop", None).unwrap();
7851
    a.bookmark_switch("develop", false).unwrap();
7852
    write(&root.join("a"), "base.txt", b"base\nd1\n");
7853
    let d1 = a.commit("d1", &[]).unwrap();
7854
    assert!(a.push("origin", false).unwrap()[0].ok);
7855
7856
    // A clone has main only; origin/develop is a name all the same.
7857
    let c_root = root.join("c");
7858
    let mut c = Repo::clone(&url, &c_root).unwrap();
7859
    assert_eq!(c.config.bookmark, "main");
7860
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
7861
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
7862
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
7863
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
7864
7865
    // Switching makes the local bookmark from origin's.
7866
    c.bookmark_switch("develop", false).unwrap();
7867
    assert_eq!(c.config.bookmark, "develop");
7868
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
7869
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
7870
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
7871
    assert!(c.bookmark_switch("nowhere", false).is_err());
7872
7873
    // Both bookmarks move on the remote; one pull takes both.
7874
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
7875
    let d2 = a.commit("d2", &[]).unwrap();
7876
    assert!(a.push("origin", false).unwrap()[0].ok);
7877
    a.bookmark_switch("main", false).unwrap();
7878
    write(&root.join("a"), "m.txt", b"m\n");
7879
    let m = a.commit("m", &[]).unwrap();
7880
    assert!(a.push("origin", false).unwrap()[0].ok);
7881
    // oxygen#117: a remote's bookmark merges without switching to it.
7882
    let f = Repo::clone(&url, &root.join("f")).unwrap();
7883
    assert!(!f.view().unwrap().bookmarks.contains_key("develop"));
7884
    let merged = f.merge("origin/develop").unwrap();
7885
    assert!(merged.changed, "{merged:?}");
7886
    assert!(
7887
        f.load_state_indexed(&f.bookmark_heads().unwrap())
7888
            .unwrap()
7889
            .contains(&d1),
7890
        "main holds develop's change"
7891
    );
7892
    assert!(f
7893
        .merge("origin/nowhere")
7894
        .unwrap_err()
7895
        .to_string()
7896
        .contains("no bookmark origin/nowhere"));
7897
    let r = c.pull("origin").unwrap();
7898
    assert!(r.changed && r.checked_out, "{r:?}");
7899
    assert_eq!(r.heads, vec![d2]);
7900
    assert_eq!(r.others, vec!["main".to_string()]);
7901
    assert!(c.resolve_heads("main").unwrap().contains(&m));
7902
    assert_eq!(
7903
        fs::read(c_root.join("base.txt")).unwrap(),
7904
        b"base\nd1\nd2\n"
7905
    );
7906
    let again = c.pull("origin").unwrap();
7907
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
7908
7909
    // A clone checks out the remote's default bookmark.
7910
    origin.config.set("workspace.bookmark", "develop").unwrap();
7911
    origin.save_config().unwrap();
7912
    let e = Repo::clone(&url, &root.join("e")).unwrap();
7913
    assert_eq!(e.config.bookmark, "develop");
7914
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
7915
    let reopened = Repo::open(&root.join("e")).unwrap();
7916
    assert_eq!(reopened.config.bookmark, "develop");
7917
    // REMOTE/NAME names the remote's bookmark to switch to.
7918
    let mut e = reopened;
7919
    e.bookmark_switch("origin/main", false).unwrap();
7920
    assert_eq!(e.config.bookmark, "main");
7921
    assert!(e.bookmark_heads().unwrap().contains(&m));
7922
}
7923
7924
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
7925
/// op restore goes back to an operation, files included, and undo takes
7926
/// the restore back whole; op revert undoes one operation alone; each
7927
/// operation's changes are described from the views.
7928
#[test]
7929
fn operations_can_be_read_restored_and_reverted() {
7930
    hermetic();
7931
    let dir = tempfile::tempdir().unwrap();
7932
    let root = dir.path();
7933
    let repo = Repo::init(root).unwrap();
7934
    write(root, "a.txt", b"a\n");
7935
    let first = repo.commit("first", &[]).unwrap();
7936
    write(root, "a.txt", b"a\nb\n");
7937
    let second = repo.commit("second", &[]).unwrap();
7938
    let at_second = repo.head_op().unwrap().0.to_hex();
7939
    repo.bookmark_create("keep", None).unwrap();
7940
    let created = repo.head_op().unwrap().0.to_hex();
7941
    write(root, "n.txt", b"n\n");
7942
    let third = repo.commit("third", &[]).unwrap();
7943
7944
    // What each operation changed.
7945
    let ops = repo.op_log().unwrap();
7946
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
7947
    assert!(
7948
        changes
7949
            .iter()
7950
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
7951
        "{changes:?}"
7952
    );
7953
    assert!(changes
7954
        .iter()
7955
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
7956
7957
    // Reading at an earlier operation.
7958
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
7959
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
7960
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
7961
    write(root, "z.txt", b"z\n");
7962
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
7963
    fs::remove_file(root.join("z.txt")).unwrap();
7964
    assert!(repo.resolve_op("zz").is_err());
7965
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
7966
7967
    // Restore goes back, files and all; undo takes it back whole.
7968
    repo.op_restore(&at_second, false).unwrap();
7969
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
7970
    assert!(!root.join("n.txt").exists());
7971
    repo.undo().unwrap();
7972
    let mut heads = repo.bookmark_heads().unwrap();
7973
    heads.sort();
7974
    let mut want = vec![second, third];
7975
    want.sort();
7976
    assert_eq!(heads, want);
7977
    assert!(
7978
        root.join("n.txt").exists(),
7979
        "the files came back with the undo"
7980
    );
7981
7982
    // Revert the bookmark's creation alone: the commit after it stays.
7983
    let r = repo.op_revert(&created).unwrap();
7984
    assert_eq!(r.reverted, vec!["keep".to_string()]);
7985
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
7986
    assert!(repo
7987
        .load_state(&repo.bookmark_heads().unwrap())
7988
        .unwrap()
7989
        .contains(&third));
7990
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
7991
    let _ = first;
7992
}
7993
7994
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
7995
/// from the status cache while every file is as the snapshot left it, and
7996
/// from a snapshot again as soon as one is not.
7997
#[test]
7998
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
7999
    hermetic();
8000
    let dir = tempfile::tempdir().unwrap();
8001
    let root = dir.path();
8002
    let repo = Repo::init(root).unwrap();
8003
    write(root, "a.txt", b"a\n");
8004
    write(root, "b.txt", b"b\n");
8005
    repo.commit("base", &[]).unwrap();
8006
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
8007
8008
    write(root, "a.txt", b"a\nmore\n");
8009
    assert_eq!(
8010
        repo.status_by_manifest().unwrap(),
8011
        None,
8012
        "no snapshot of the edit yet"
8013
    );
8014
    let snap = repo.snapshot_status("oxy status").unwrap();
8015
    assert_eq!(snap.statuses.len(), 1);
8016
    let cached = repo
8017
        .status_by_manifest()
8018
        .unwrap()
8019
        .expect("answered from the cache");
8020
    assert_eq!(cached.len(), 1);
8021
    assert_eq!(
8022
        (cached[0].path.as_str(), cached[0].status),
8023
        ("a.txt", ChangeStatus::Modified)
8024
    );
8025
8026
    // Any further change sends status back to a snapshot.
8027
    write(root, "a.txt", b"a\nmore\nand more\n");
8028
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
8029
    repo.snapshot_status("oxy status").unwrap();
8030
    assert!(repo.status_by_manifest().unwrap().is_some());
8031
    write(root, "new.txt", b"n\n");
8032
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
8033
    fs::remove_file(root.join("new.txt")).unwrap();
8034
    assert!(
8035
        repo.status_by_manifest().unwrap().is_some(),
8036
        "back as it was"
8037
    );
8038
    fs::remove_file(root.join("b.txt")).unwrap();
8039
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
8040
    write(root, "b.txt", b"b\n");
8041
8042
    // A commit leaves nothing uncommitted: clean again, no cache needed.
8043
    repo.snapshot_status("oxy status").unwrap();
8044
    repo.commit("more", &[]).unwrap();
8045
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
8046
}
8047
8048
/// oxygen#41: while the status cache holds, the working copy's diff is
8049
/// rendered from the stored working-copy change, and says exactly what a
8050
/// snapshot's diff says.
8051
#[test]
8052
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
8053
    hermetic();
8054
    let dir = tempfile::tempdir().unwrap();
8055
    let root = dir.path();
8056
    let repo = Repo::init(root).unwrap();
8057
    write(root, "a.txt", b"one\ntwo\nthree\n");
8058
    write(root, "gone.txt", b"bye\n");
8059
    repo.commit("base", &[]).unwrap();
8060
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
8061
    write(root, "new.txt", b"hello\n");
8062
    fs::remove_file(root.join("gone.txt")).unwrap();
8063
    let snap = repo.snapshot_status("oxy status").unwrap();
8064
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
8065
    assert!(
8066
        repo.status_by_manifest().unwrap().is_some(),
8067
        "the cache holds"
8068
    );
8069
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
8070
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
8071
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
8072
8073
    // Committed, nothing changes: the diff is empty without loading the
8074
    // base (oxygen#94), and the same as rendering it.
8075
    repo.commit("all", &[]).unwrap();
8076
    repo.snapshot_status("oxy status").unwrap();
8077
    assert!(repo.status_by_manifest().unwrap().is_some());
8078
    assert!(repo
8079
        .working_copy_with_base_unless_unchanged()
8080
        .unwrap()
8081
        .is_none());
8082
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
8083
    assert_eq!(render_change(&wc, &base, &snapshot), "");
8084
    assert!(repo.diff_files(None).unwrap().is_empty());
8085
}
8086
8087
/// oxygen#41: a manifest written from a walk keeps every directory's time;
8088
/// while none has moved, the check stats the tracked files without listing
8089
/// the tree, and a file added or removed anywhere moves its directory's
8090
/// time, so the tree is listed again.
8091
#[test]
8092
fn the_manifest_check_skips_listing_while_no_directory_changed() {
8093
    hermetic();
8094
    let dir = tempfile::tempdir().unwrap();
8095
    let root = dir.path();
8096
    let repo = Repo::init(root).unwrap();
8097
    write(root, "a.txt", b"a\n");
8098
    write(root, "sub/deep/b.txt", b"b\n");
8099
    repo.commit("base", &[]).unwrap();
8100
    // Out of the racy window: every file and directory a minute old.
8101
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
8102
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
8103
        fs::File::open(root.join(p))
8104
            .unwrap()
8105
            .set_modified(old)
8106
            .unwrap();
8107
    }
8108
    repo.snapshot_status("oxy status").unwrap();
8109
    repo.write_manifest(false, false).unwrap();
8110
    let m = repo.read_manifest().unwrap().unwrap().2;
8111
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
8112
    assert_eq!(
8113
        repo.disk_differs_by_dirs(&m),
8114
        Some(false),
8115
        "no listing needed"
8116
    );
8117
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
8118
8119
    // A same-size edit with a new time: found by its stat.
8120
    write(root, "sub/deep/b.txt", b"c\n");
8121
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
8122
    write(root, "sub/deep/b.txt", b"b\n");
8123
    fs::File::open(root.join("sub/deep/b.txt"))
8124
        .unwrap()
8125
        .set_modified(old)
8126
        .unwrap();
8127
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
8128
8129
    // A new file moves its directory's time: the tree must be listed.
8130
    write(root, "sub/deep/new.txt", b"n\n");
8131
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
8132
    assert_eq!(repo.status_by_manifest().unwrap(), None);
8133
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
8134
    // A removed one too.
8135
    fs::remove_file(root.join("a.txt")).unwrap();
8136
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
8137
}
8138
8139
/// oxygen#41: a commit right after a status takes the snapshot the status
8140
/// left (the status cache holds) rather than walking again, and commits
8141
/// exactly what a snapshot would have.
8142
#[test]
8143
fn a_commit_after_a_status_uses_the_cached_snapshot() {
8144
    hermetic();
8145
    let dir = tempfile::tempdir().unwrap();
8146
    let root = dir.path();
8147
    let repo = Repo::init(root).unwrap();
8148
    write(root, "a.txt", b"a\nb\n");
8149
    write(root, ".oxyattributes", b"*.bin binary\n");
8150
    repo.commit("base", &[]).unwrap();
8151
    write(root, "a.txt", b"a\nB\n");
8152
    write(root, "new.txt", b"new\n");
8153
    let snap = repo.snapshot_status("oxy status").unwrap();
8154
    let cached = repo
8155
        .snapshot_from_cache()
8156
        .unwrap()
8157
        .expect("the cache holds");
8158
    assert_eq!(cached.wc_hash, snap.wc_hash);
8159
    assert_eq!(cached.statuses, snap.statuses);
8160
    assert!(
8161
        !cached.attributes.is_empty(),
8162
        "the .oxyattributes file was read"
8163
    );
8164
    let h = repo.commit("edit", &[]).unwrap();
8165
    let c = repo.store().get_change(&h).unwrap();
8166
    assert_eq!(
8167
        c.tree_ops.len() + c.edits.len(),
8168
        snap.wc.tree_ops.len() + snap.wc.edits.len()
8169
    );
8170
    assert_eq!(
8171
        repo.status_by_manifest().unwrap(),
8172
        Some(vec![]),
8173
        "clean after the commit"
8174
    );
8175
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
8176
}
8177
8178
/// oxygen#41: a clean check that verified racy entries restamps the
8179
/// manifest, so later checks can trust them, and a same-size rewrite
8180
/// straight afterwards is still found: entries within two seconds of the
8181
/// new time stay racy.
8182
#[test]
8183
fn a_verified_clean_check_restamps_the_manifest_safely() {
8184
    hermetic();
8185
    let dir = tempfile::tempdir().unwrap();
8186
    let root = dir.path();
8187
    let repo = Repo::init(root).unwrap();
8188
    write(root, "a.txt", b"one\n");
8189
    repo.commit("one", &[]).unwrap();
8190
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
8191
    assert!(repo.clean_by_manifest().unwrap());
8192
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
8193
    assert!(after > before, "restamped");
8194
    write(root, "a.txt", b"two\n");
8195
    assert!(
8196
        !repo.clean_by_manifest().unwrap(),
8197
        "a same-size rewrite is still seen"
8198
    );
8199
}
8200
8201
/// oxygen#35: a history-only state keeps no inserted text. It reads a
8202
/// stored insert's text blob only when it builds that file's graph, and
8203
/// builds the same graph a full load does.
8204
#[test]
8205
fn history_only_states_read_text_only_for_the_graphs_they_build() {
8206
    hermetic();
8207
    let dir = tempfile::tempdir().unwrap();
8208
    let root = dir.path();
8209
    let repo = Repo::init(root).unwrap();
8210
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
8211
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
8212
    write(root, "big.txt", big.as_bytes());
8213
    write(root, "other.txt", other.as_bytes());
8214
    let h = repo.commit("two large files", &[]).unwrap();
8215
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
8216
    let h2 = repo.commit("append", &[]).unwrap();
8217
8218
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
8219
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
8220
        FileContent::Text { bytes, .. } => bytes.clone(),
8221
        other => panic!("{other:?}"),
8222
    };
8223
    // Built on demand, every graph renders as the full load's.
8224
    let mut hist = repo.load_state_history(&[h2]).unwrap();
8225
    let big_node = full.files["big.txt"].node;
8226
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
8227
    repo.load_all_graphs(&mut hist).unwrap();
8228
    let rendered = hist.materialize();
8229
    for p in ["big.txt", "other.txt"] {
8230
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
8231
    }
8232
8233
    // Without other.txt's text blob, history still loads and big.txt still
8234
    // builds: nothing read the other text.
8235
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
8236
    assert_eq!(texts.len(), 2);
8237
    let content = |r: &ObjectRef| -> Vec<u8> {
8238
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
8239
        blob.chunks
8240
            .iter()
8241
            .flat_map(|c| repo.store().get(c).unwrap().1)
8242
            .collect()
8243
    };
8244
    let other_text = texts
8245
        .iter()
8246
        .filter_map(|t| match t {
8247
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
8248
            _ => None,
8249
        })
8250
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
8251
        .unwrap();
8252
    repo.store().remove_loose_for_test(&other_text).unwrap();
8253
    let mut hist = repo.load_state_history(&[h2]).unwrap();
8254
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
8255
    assert!(repo
8256
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
8257
        .is_err());
8258
}
8259
8260
/// oxygen#35: the first status after a commit read and rendered every
8261
/// file (79 s and more than 14 GB on the Linux tree), because the
8262
/// manifest had no graph keys for files the commit added.
8263
#[test]
8264
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
8265
    use std::os::unix::fs::PermissionsExt;
8266
    hermetic();
8267
    let dir = tempfile::tempdir().unwrap();
8268
    let root = dir.path();
8269
    let repo = Repo::init(root).unwrap();
8270
    let files = ["a.txt", "b.txt", "d/c.txt"];
8271
    for p in files {
8272
        write(root, p, format!("{p}\n").as_bytes());
8273
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
8274
        fs::File::options()
8275
            .write(true)
8276
            .open(root.join(p))
8277
            .unwrap()
8278
            .set_modified(old)
8279
            .unwrap();
8280
    }
8281
    repo.commit("added", &[]).unwrap();
8282
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
8283
    assert!(
8284
        m.entries.values().all(|e| e.graph.is_some()),
8285
        "keys recorded at commit"
8286
    );
8287
    // Unreadable files prove the next status reads none of them.
8288
    for p in files {
8289
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
8290
    }
8291
    let snap = repo.snapshot_status("status").unwrap();
8292
    for p in files {
8293
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
8294
    }
8295
    assert!(!snap.changed && snap.statuses.is_empty());
8296
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
8297
}
8298
8299
/// oxygen#35: a checkout reads, renders and writes only the files whose
8300
/// graphs differ, and renders the rest a batch at a time.
8301
#[test]
8302
fn checkout_touches_only_what_differs_and_renders_in_batches() {
8303
    use std::os::unix::fs::PermissionsExt;
8304
    hermetic();
8305
    let dir = tempfile::tempdir().unwrap();
8306
    let root = dir.path();
8307
    let origin = root.join("origin");
8308
    let mut repo = Repo::init(&origin).unwrap();
8309
    // More files than one batch holds.
8310
    let n = 2100;
8311
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
8312
    for i in 0..n {
8313
        let p = format!("f/{i:04}.txt");
8314
        write(&origin, &p, format!("file {i}\n").as_bytes());
8315
        fs::File::options()
8316
            .write(true)
8317
            .open(origin.join(&p))
8318
            .unwrap()
8319
            .set_modified(old)
8320
            .unwrap();
8321
    }
8322
    repo.commit("many", &[]).unwrap();
8323
    repo.bookmark_create("feature", None).unwrap();
8324
    repo.bookmark_switch("feature", false).unwrap();
8325
    write(&origin, "f/0007.txt", b"changed\n");
8326
    repo.commit("one change", &[]).unwrap();
8327
8328
    // Switching back to main must not read the unchanged files.
8329
    for i in 0..n {
8330
        if i != 7 {
8331
            let p = origin.join(format!("f/{i:04}.txt"));
8332
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
8333
        }
8334
    }
8335
    let r = repo.bookmark_switch("main", false).unwrap();
8336
    for i in 0..n {
8337
        let p = origin.join(format!("f/{i:04}.txt"));
8338
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
8339
    }
8340
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
8341
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
8342
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
8343
8344
    // A clone renders every file, across batches.
8345
    let c = root.join("clone");
8346
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
8347
    for i in [0, 2047, 2048, n - 1] {
8348
        assert_eq!(
8349
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
8350
            format!("file {i}\n").as_bytes()
8351
        );
8352
    }
8353
    let cloned = Repo::open(&c).unwrap();
8354
    assert!(cloned
8355
        .snapshot_status("status")
8356
        .unwrap()
8357
        .statuses
8358
        .is_empty());
8359
}
8360
8361
/// A file written just before the manifest (inside the racy window) is
8362
/// checked by its hash: trusted when equal, caught when edited in place
8363
/// with the same size and time.
8364
#[test]
8365
fn a_racy_manifest_entry_is_checked_by_hash() {
8366
    hermetic();
8367
    let dir = tempfile::tempdir().unwrap();
8368
    let root = dir.path();
8369
    let repo = Repo::init(root).unwrap();
8370
    write(root, "a.txt", b"one\n");
8371
    repo.commit("fresh", &[]).unwrap();
8372
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
8373
    let t = fs::metadata(root.join("a.txt"))
8374
        .unwrap()
8375
        .modified()
8376
        .unwrap();
8377
    write(root, "a.txt", b"two\n");
8378
    fs::File::options()
8379
        .write(true)
8380
        .open(root.join("a.txt"))
8381
        .unwrap()
8382
        .set_modified(t)
8383
        .unwrap();
8384
    assert!(
8385
        !repo.clean_by_manifest().unwrap(),
8386
        "same size and time, other bytes"
8387
    );
8388
    assert_eq!(
8389
        statuses(&repo.snapshot_status("status").unwrap()),
8390
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
8391
    );
8392
}
8393
8394
/// A fetch on one machine moves changes as stored, text blobs among the
8395
/// objects; a change whose text blob did not come is refused, not stored.
8396
#[test]
8397
fn a_raw_bundle_without_a_changes_text_is_refused() {
8398
    hermetic();
8399
    let dir = tempfile::tempdir().unwrap();
8400
    let root = dir.path();
8401
    let a = Repo::init(&root.join("a")).unwrap();
8402
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
8403
    write(&root.join("a"), "big.txt", big.as_bytes());
8404
    let h = a.commit("big", &[]).unwrap();
8405
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
8406
    assert_eq!(bundle.raw_changes.len(), 1);
8407
    assert!(bundle.changes.is_empty());
8408
    let b = Repo::init(&root.join("b")).unwrap();
8409
    let mut without = bundle.clone();
8410
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
8411
    let e = b.import_bundle(&without, false).unwrap_err();
8412
    assert!(e.to_string().contains("came without its text blob"), "{e}");
8413
    assert!(!b.store().has(&h));
8414
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
8415
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
8416
}
8417
8418
/// oxygen#30 (vscode): a directory deleted in one line of history and made
8419
/// again was a second node for one Git path, so a file moved into it on
8420
/// another line, where the first node still stood, ended up in two places.
8421
/// An import now brings the directory back rather than make a new one.
8422
#[test]
8423
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
8424
    hermetic();
8425
    if std::process::Command::new("git")
8426
        .arg("--version")
8427
        .output()
8428
        .is_err()
8429
    {
8430
        eprintln!("git not installed; skipping");
8431
        return;
8432
    }
8433
    let dir = tempfile::tempdir().unwrap();
8434
    let root = dir.path();
8435
    let g = root.join("src.git");
8436
    fs::create_dir_all(&g).unwrap();
8437
    let git = |args: &[&str]| -> String {
8438
        let out = std::process::Command::new("git")
8439
            .arg("-C")
8440
            .arg(&g)
8441
            .args([
8442
                "-c",
8443
                "user.name=Grace",
8444
                "-c",
8445
                "[email protected]",
8446
                "-c",
8447
                "commit.gpgsign=false",
8448
            ])
8449
            .args(args)
8450
            .output()
8451
            .unwrap();
8452
        assert!(
8453
            out.status.success(),
8454
            "git {args:?}: {}",
8455
            String::from_utf8_lossy(&out.stderr)
8456
        );
8457
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8458
    };
8459
    git(&["init", "-q", "-b", "main"]);
8460
    write(&g, "d/a.txt", b"a\n");
8461
    write(&g, "c/x.txt", b"x\n");
8462
    git(&["add", "."]);
8463
    git(&["commit", "-qm", "base"]);
8464
    // One line: move x into d while d still stands.
8465
    git(&["checkout", "-qb", "side"]);
8466
    git(&["mv", "c/x.txt", "d/x.txt"]);
8467
    git(&["commit", "-qm", "x into d"]);
8468
    // The other: d goes, comes back, and x moves into it too.
8469
    git(&["checkout", "-q", "main"]);
8470
    git(&["rm", "-q", "d/a.txt"]);
8471
    git(&["commit", "-qm", "d goes"]);
8472
    write(&g, "d/b.txt", b"b\n");
8473
    git(&["add", "."]);
8474
    git(&["commit", "-qm", "d comes back"]);
8475
    git(&["mv", "c/x.txt", "d/x.txt"]);
8476
    git(&["commit", "-qm", "x into d again"]);
8477
    git(&["merge", "-q", "--no-edit", "side"]);
8478
8479
    let repo = Repo::init(&root.join("o")).unwrap();
8480
    repo.import_git(&g, "main").unwrap();
8481
    let v = repo.verify_git_import(&g, "main").unwrap();
8482
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8483
    let st = repo
8484
        .load_state_history(&repo.bookmark_heads().unwrap())
8485
        .unwrap();
8486
    let view = st.tree().view();
8487
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8488
    // The directory is the one the first commit made.
8489
    // Commits made in one second tie on time: find the first by its message.
8490
    let first = repo
8491
        .log()
8492
        .unwrap()
8493
        .into_iter()
8494
        .find(|e| e.change.message.starts_with("base"))
8495
        .unwrap();
8496
    let base = repo
8497
        .load_state_history(&[first.hash])
8498
        .unwrap()
8499
        .tree()
8500
        .view();
8501
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
8502
}
8503
8504
/// oxygen#30, the rest: a placement left under a directory another line
8505
/// removed is out of sight, so no diff reaches it; the merge that settles
8506
/// where the file is retires it.
8507
#[test]
8508
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
8509
    hermetic();
8510
    if std::process::Command::new("git")
8511
        .arg("--version")
8512
        .output()
8513
        .is_err()
8514
    {
8515
        eprintln!("git not installed; skipping");
8516
        return;
8517
    }
8518
    let dir = tempfile::tempdir().unwrap();
8519
    let root = dir.path();
8520
    let g = root.join("src.git");
8521
    fs::create_dir_all(&g).unwrap();
8522
    let run = |args: &[&str]| {
8523
        std::process::Command::new("git")
8524
            .arg("-C")
8525
            .arg(&g)
8526
            .args([
8527
                "-c",
8528
                "user.name=Grace",
8529
                "-c",
8530
                "[email protected]",
8531
                "-c",
8532
                "commit.gpgsign=false",
8533
            ])
8534
            .args(args)
8535
            .output()
8536
            .unwrap()
8537
    };
8538
    let git = |args: &[&str]| {
8539
        let out = run(args);
8540
        assert!(
8541
            out.status.success(),
8542
            "git {args:?}: {}",
8543
            String::from_utf8_lossy(&out.stderr)
8544
        );
8545
    };
8546
    git(&["init", "-q", "-b", "main"]);
8547
    write(&g, "c/x.txt", b"x\n");
8548
    write(&g, "keep.txt", b"k\n");
8549
    git(&["add", "."]);
8550
    git(&["commit", "-qm", "base"]);
8551
    // One line renames the file within c; the other moves it out of c,
8552
    // which goes.
8553
    git(&["checkout", "-qb", "side"]);
8554
    git(&["mv", "c/x.txt", "c/y.txt"]);
8555
    git(&["commit", "-qm", "rename within c"]);
8556
    git(&["checkout", "-q", "main"]);
8557
    fs::create_dir_all(g.join("n")).unwrap();
8558
    git(&["mv", "c/x.txt", "n/x.txt"]);
8559
    git(&["commit", "-qm", "move out of c"]);
8560
    // Git cannot merge the two renames; the merge keeps n/x.txt.
8561
    let _ = run(&["merge", "-q", "side"]);
8562
    let _ = run(&[
8563
        "rm",
8564
        "-q",
8565
        "--cached",
8566
        "--ignore-unmatch",
8567
        "c/y.txt",
8568
        "c/x.txt",
8569
    ]);
8570
    let _ = std::fs::remove_dir_all(g.join("c"));
8571
    write(&g, "n/x.txt", b"x\n");
8572
    git(&["add", "-A"]);
8573
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
8574
8575
    let repo = Repo::init(&root.join("o")).unwrap();
8576
    repo.import_git(&g, "main").unwrap();
8577
    let v = repo.verify_git_import(&g, "main").unwrap();
8578
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8579
    let st = repo
8580
        .load_state_history(&repo.bookmark_heads().unwrap())
8581
        .unwrap();
8582
    let view = st.tree().view();
8583
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8584
    assert!(view.entries.contains_key("n/x.txt"));
8585
}
8586
8587
/// oxygen#30, orphans: a file added on one line into a directory the other
8588
/// line removed is placed where the tree cannot show it; Git's merge keeps
8589
/// the file, and the import's merge leaves exactly one of it.
8590
#[test]
8591
fn git_import_merge_leaves_no_orphan_behind() {
8592
    hermetic();
8593
    if std::process::Command::new("git")
8594
        .arg("--version")
8595
        .output()
8596
        .is_err()
8597
    {
8598
        eprintln!("git not installed; skipping");
8599
        return;
8600
    }
8601
    let dir = tempfile::tempdir().unwrap();
8602
    let root = dir.path();
8603
    let g = root.join("src.git");
8604
    fs::create_dir_all(&g).unwrap();
8605
    let git = |args: &[&str]| {
8606
        let out = std::process::Command::new("git")
8607
            .arg("-C")
8608
            .arg(&g)
8609
            .args([
8610
                "-c",
8611
                "user.name=Grace",
8612
                "-c",
8613
                "[email protected]",
8614
                "-c",
8615
                "commit.gpgsign=false",
8616
            ])
8617
            .args(args)
8618
            .output()
8619
            .unwrap();
8620
        assert!(
8621
            out.status.success(),
8622
            "git {args:?}: {}",
8623
            String::from_utf8_lossy(&out.stderr)
8624
        );
8625
    };
8626
    git(&["init", "-q", "-b", "main"]);
8627
    write(&g, "d/f.txt", b"f\n");
8628
    write(&g, "keep.txt", b"k\n");
8629
    git(&["add", "."]);
8630
    git(&["commit", "-qm", "base"]);
8631
    git(&["checkout", "-qb", "side"]);
8632
    write(&g, "d/new.txt", b"new\n");
8633
    git(&["add", "."]);
8634
    git(&["commit", "-qm", "add into d"]);
8635
    git(&["checkout", "-q", "main"]);
8636
    git(&["rm", "-q", "d/f.txt"]);
8637
    git(&["commit", "-qm", "d goes"]);
8638
    git(&["merge", "-q", "--no-edit", "side"]);
8639
8640
    let repo = Repo::init(&root.join("o")).unwrap();
8641
    repo.import_git(&g, "main").unwrap();
8642
    let v = repo.verify_git_import(&g, "main").unwrap();
8643
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8644
    let st = repo
8645
        .load_state_history(&repo.bookmark_heads().unwrap())
8646
        .unwrap();
8647
    let view = st.tree().view();
8648
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8649
    assert!(view.entries.contains_key("d/new.txt"));
8650
}
8651
8652
/// fsck checks a change's text as the blobs it is stored in, without
8653
/// decoding it: a missing text blob is an error named for the change.
8654
#[test]
8655
fn fsck_names_a_missing_text_blob() {
8656
    hermetic();
8657
    let dir = tempfile::tempdir().unwrap();
8658
    let root = dir.path();
8659
    let repo = Repo::init(root).unwrap();
8660
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
8661
    write(root, "big.txt", big.as_bytes());
8662
    let h = repo.commit("big", &[]).unwrap();
8663
    assert_eq!(repo.fsck().unwrap().errors(), 0);
8664
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
8665
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
8666
        panic!("a stored text")
8667
    };
8668
    repo.store().remove_loose_for_test(&b).unwrap();
8669
    let rep = repo.fsck().unwrap();
8670
    assert!(rep.errors() > 0);
8671
    assert!(
8672
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
8673
        "{:?}",
8674
        rep.problems
8675
    );
8676
}
8677
8678
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
8679
/// reached with that remote's token and CA (a private subrepo then clones
8680
/// for anyone who can read the parent); another hub gets none of them.
8681
#[test]
8682
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
8683
    hermetic();
8684
    let dir = tempfile::tempdir().unwrap();
8685
    let mut repo = Repo::init(dir.path()).unwrap();
8686
    repo.config
8687
        .set(
8688
            "remote.origin.url",
8689
            "https://Hub.example:7343/doomsdayone/metalgear",
8690
        )
8691
        .unwrap();
8692
    repo.config.set("remote.origin.token", "secret").unwrap();
8693
    repo.config
8694
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
8695
        .unwrap();
8696
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
8697
    assert_eq!(same.token.as_deref(), Some("secret"));
8698
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
8699
    for other in [
8700
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
8701
        "https://hub.example/doomsdayone/rstar-api",
8702
        "http://hub.example:7343/doomsdayone/rstar-api",
8703
    ] {
8704
        let o = repo.credentials_for(other);
8705
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
8706
    }
8707
}
8708
8709
/// oxygen#47: a remote with no token of its own uses the user's credential
8710
/// store for its hub, and a nested checkout finds its parent's remote
8711
/// token there instead of keeping a copy.
8712
#[test]
8713
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
8714
    hermetic();
8715
    let home = tempfile::tempdir().unwrap();
8716
    let dir = tempfile::tempdir().unwrap();
8717
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
8718
    parent
8719
        .config
8720
        .set("remote.origin.url", "https://hub.example/o/parent")
8721
        .unwrap();
8722
    parent.save_config().unwrap();
8723
    assert_eq!(parent.remote_options("origin").token, None);
8724
    crate::credentials::Credentials::at(home.path())
8725
        .save("https://hub.example", "stored", Some("andy"), None)
8726
        .unwrap();
8727
    assert_eq!(
8728
        parent.remote_options("origin").token.as_deref(),
8729
        Some("stored")
8730
    );
8731
8732
    let empty_home = tempfile::tempdir().unwrap();
8733
    let nested = dir.path().join("deps").join("child");
8734
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
8735
    child
8736
        .config
8737
        .set("remote.origin.url", "https://hub.example/o/child")
8738
        .unwrap();
8739
    child.save_config().unwrap();
8740
    assert_eq!(child.remote_options("origin").token, None);
8741
    parent
8742
        .config
8743
        .set("remote.origin.token", "checkout")
8744
        .unwrap();
8745
    parent.save_config().unwrap();
8746
    assert_eq!(
8747
        child.remote_options("origin").token.as_deref(),
8748
        Some("checkout")
8749
    );
8750
    // Another hub's checkout token is not borrowed.
8751
    child
8752
        .config
8753
        .set("remote.origin.url", "https://other.example/o/child")
8754
        .unwrap();
8755
    assert_eq!(child.remote_options("origin").token, None);
8756
}
8757
8758
#[test]
8759
fn the_metadata_cache_survives_a_torn_tail() {
8760
    hermetic();
8761
    let dir = tempfile::tempdir().unwrap();
8762
    let root = dir.path();
8763
    let repo = Repo::init(root).unwrap();
8764
    write(root, "a.txt", b"1\n");
8765
    let h = repo.commit("first", &[]).unwrap();
8766
    let meta = repo.store().get_change_meta(&h).unwrap();
8767
    let cache = repo.store().dir().join("metas");
8768
    let len = fs::metadata(&cache).unwrap().len();
8769
    assert!(len > 0, "a change read is cached");
8770
    // A torn record at the end: the cache reads up to it and cuts it off.
8771
    fs::OpenOptions::new()
8772
        .append(true)
8773
        .open(&cache)
8774
        .unwrap()
8775
        .write_all(&[7; 20])
8776
        .unwrap();
8777
    let again = Repo::open(root).unwrap();
8778
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
8779
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
8780
}
8781
8782
#[test]
8783
fn a_manifest_that_does_not_check_reads_as_none() {
8784
    hermetic();
8785
    let dir = tempfile::tempdir().unwrap();
8786
    let root = dir.path();
8787
    let repo = Repo::init(root).unwrap();
8788
    write(root, "a.txt", b"1\n");
8789
    repo.commit("first", &[]).unwrap();
8790
    let path = repo.manifest_path();
8791
    let mut bytes = fs::read(&path).unwrap();
8792
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
8793
    let last = bytes.len() - 1;
8794
    bytes[last] ^= 1;
8795
    fs::write(&path, &bytes).unwrap();
8796
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
8797
    // The next status reads the files and writes it again.
8798
    let again = Repo::open(root).unwrap();
8799
    assert!(!again.snapshot("status").unwrap().changed);
8800
    assert!(again.read_manifest().unwrap().is_some());
8801
}
8802
8803
#[test]
8804
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
8805
    hermetic();
8806
    let dir = tempfile::tempdir().unwrap();
8807
    let root = dir.path();
8808
    let repo = Repo::init(root).unwrap();
8809
    write(root, "a.txt", b"1\n");
8810
    write(root, "b.txt", b"2\n");
8811
    // b.txt outside the racy window, so snapshots take it as unchanged.
8812
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
8813
    fs::File::options()
8814
        .write(true)
8815
        .open(root.join("b.txt"))
8816
        .unwrap()
8817
        .set_modified(old)
8818
        .unwrap();
8819
    repo.commit("first", &[]).unwrap();
8820
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
8821
    repo.snapshot_status("status").unwrap();
8822
    write(root, "a.txt", b"1\n2\n");
8823
    repo.commit("second", &[]).unwrap();
8824
    assert!(
8825
        repo.clean_by_manifest().unwrap(),
8826
        "after a commit of one file"
8827
    );
8828
    // Edited, seen by a status, edited again, then committed: the status
8829
    // left the first edit's stat, which the commit must not keep.
8830
    write(root, "a.txt", b"1\n2\n3\n");
8831
    repo.snapshot_status("status").unwrap();
8832
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
8833
    repo.commit("third", &[]).unwrap();
8834
    assert!(
8835
        repo.clean_by_manifest().unwrap(),
8836
        "after an edit a status saw"
8837
    );
8838
}
8839
8840
#[test]
8841
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
8842
    hermetic();
8843
    let dir = tempfile::tempdir().unwrap();
8844
    let root = dir.path();
8845
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
8846
    write(root, "a.txt", b"1\n2\n");
8847
    let a = repo.commit("A", &[]).unwrap();
8848
    repo.bookmark_create("develop", Some(&[a])).unwrap();
8849
    write(root, "a.txt", b"1\nX\n");
8850
    let c = repo.commit("C: 2 to X", &[]).unwrap();
8851
    repo.bookmark_switch("develop", false).unwrap();
8852
    write(root, "a.txt", b"1\nY\n");
8853
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
8854
    repo.bookmark_switch("main", false).unwrap();
8855
8856
    let err = repo.rebase(&c, &[d]).unwrap_err();
8857
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
8858
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
8859
    assert!(r.changed && r.checked_out);
8860
    let snap = repo.snapshot_status("status").unwrap();
8861
    assert!(
8862
        snap.base_snapshot.is_conflicted(),
8863
        "the conflict is in the working copy"
8864
    );
8865
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
8866
    assert!(text.contains('X') && text.contains('Y'), "{text}");
8867
8868
    write(root, "a.txt", b"1\nXY\n");
8869
    repo.commit("Resolve", &[]).unwrap();
8870
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
8871
    assert!(st.contains(&c) && st.contains(&d));
8872
    let files = st.materialize().files;
8873
    assert!(!files["a.txt"].is_conflicted());
8874
    assert!(
8875
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
8876
    );
8877
8878
    // A change the current bookmark does not hold is refused.
8879
    repo.bookmark_switch("develop", false).unwrap();
8880
    write(root, "b.txt", b"b\n");
8881
    let e = repo.commit("E", &[]).unwrap();
8882
    repo.bookmark_switch("main", false).unwrap();
8883
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
8884
    assert!(
8885
        err.to_string().contains("not on the current bookmark"),
8886
        "{err}"
8887
    );
8888
}
8889
8890
#[test]
8891
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
8892
    hermetic();
8893
    let dir = tempfile::tempdir().unwrap();
8894
    let root = dir.path();
8895
    let repo = Repo::init(root).unwrap();
8896
    write(root, "a.txt", b"a\n");
8897
    write(root, "kept.log", b"tracked\n");
8898
    repo.commit("first", &[]).unwrap();
8899
    write(root, "build.log", b"made\n");
8900
    let snap = repo.snapshot_status("status").unwrap();
8901
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
8902
    // A rule written afterwards leaves the added file out again, while the
8903
    // committed one stays tracked.
8904
    write(root, ".gitignore", b"*.log\n");
8905
    let snap = repo.snapshot_status("status").unwrap();
8906
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
8907
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
8908
    write(root, "kept.log", b"tracked, edited\n");
8909
    let snap = repo.snapshot_status("status").unwrap();
8910
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
8911
}
8912
8913
#[test]
8914
fn shed_graphs_come_back_the_same() {
8915
    hermetic();
8916
    let dir = tempfile::tempdir().unwrap();
8917
    let root = dir.path();
8918
    let repo = Repo::init(root).unwrap();
8919
    write(root, "a.txt", b"1\n2\n3\n");
8920
    write(root, "b.txt", b"x\n");
8921
    repo.commit("first", &[]).unwrap();
8922
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
8923
    repo.commit("second", &[]).unwrap();
8924
    let heads = repo.bookmark_heads().unwrap();
8925
    let mut st = repo.load_state_history(&heads).unwrap();
8926
    let view = st.tree().view();
8927
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
8928
        .iter()
8929
        .map(|p| view.entries[*p].node)
8930
        .collect();
8931
    repo.load_graphs_of(&mut st, &nodes).unwrap();
8932
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
8933
    assert_eq!(st.built_count(), 2);
8934
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
8935
    assert_eq!((shed, st.built_count()), (2, 0));
8936
    // A later change applies on top of the shed history.
8937
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
8938
    let h3 = repo.commit("third", &[]).unwrap();
8939
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
8940
    st.add_known(h3, skeleton, texts);
8941
    repo.load_graphs_of(&mut st, &nodes).unwrap();
8942
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
8943
    assert_eq!(after[1], before[1]);
8944
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
8945
}
8946
8947
#[test]
8948
fn many_edited_files_diff_in_parallel() {
8949
    // Enough edited files that the builder diffs them in parallel; the
8950
    // commit must hold exactly what is on disk, and a second snapshot
8951
    // must find nothing left to commit.
8952
    hermetic();
8953
    let dir = tempfile::tempdir().unwrap();
8954
    let root = dir.path();
8955
    let repo = Repo::init(root).unwrap();
8956
    let text = |i: usize, round: usize| {
8957
        let mut s = String::new();
8958
        for line in 0..50 {
8959
            if round > 0 && line % 7 == i % 7 {
8960
                s.push_str(&format!("edited {round} {i} {line}\n"));
8961
            } else {
8962
                s.push_str(&format!("file {i} line {line}\n"));
8963
            }
8964
        }
8965
        if round > 0 && i.is_multiple_of(3) {
8966
            s.push_str("appended\n");
8967
        }
8968
        s
8969
    };
8970
    for i in 0..40 {
8971
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
8972
    }
8973
    repo.commit("first", &[]).unwrap();
8974
    for i in 0..40 {
8975
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
8976
    }
8977
    let h = repo.commit("edit every file", &[]).unwrap();
8978
    let snap = repo.load_state(&[h]).unwrap().materialize();
8979
    for i in 0..40 {
8980
        let want = text(i, 1);
8981
        assert!(
8982
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
8983
            "d/f{i}.txt as committed"
8984
        );
8985
    }
8986
    assert!(
8987
        repo.commit("nothing", &[]).is_err(),
8988
        "nothing left to commit"
8989
    );
8990
}
8991
8992
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
8993
/// is known (fetch printed "up to date" while main was behind), a change
8994
/// only fetched resolves and says where it is, and a checkout whose only
8995
/// remote is not `origin` uses that one.
8996
#[test]
8997
fn a_fetched_change_shows_as_behind_and_resolves() {
8998
    hermetic();
8999
    let dir = tempfile::tempdir().unwrap();
9000
    let root = dir.path();
9001
    let origin = Repo::init(&root.join("origin")).unwrap();
9002
    drop(origin);
9003
    let url = root.join("origin").to_string_lossy().to_string();
9004
    let a = Repo::clone(&url, &root.join("a"))
9005
        .unwrap()
9006
        .with_home(root.join("home-a"));
9007
    write(&root.join("a"), "f.txt", b"one\n");
9008
    a.commit("one", &[]).unwrap();
9009
    a.push("origin", false).unwrap();
9010
    let b = Repo::clone(&url, &root.join("b"))
9011
        .unwrap()
9012
        .with_home(root.join("home-b"));
9013
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
9014
9015
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
9016
    let h2 = a.commit("two", &[]).unwrap();
9017
    a.push("origin", false).unwrap();
9018
    b.fetch("origin").unwrap();
9019
    // Fetched, not pulled: one behind, the change found and placed.
9020
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
9021
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
9022
    assert_eq!(
9023
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
9024
            .unwrap(),
9025
        h2
9026
    );
9027
    assert_eq!(
9028
        b.remote_only_location(&h2).unwrap().as_deref(),
9029
        Some("origin/main")
9030
    );
9031
    // Fetching again changes nothing: still behind, which is what the
9032
    // CLI now says rather than "up to date".
9033
    b.fetch("origin").unwrap();
9034
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
9035
    b.pull("origin").unwrap();
9036
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
9037
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
9038
9039
    // One remote, not called origin: it is the default.
9040
    let mut c = Repo::init(&root.join("c")).unwrap();
9041
    assert_eq!(c.default_remote(), "origin");
9042
    c.config.set("remote.earth.url", &url).unwrap();
9043
    assert_eq!(c.default_remote(), "earth");
9044
    c.config.set("remote.origin.url", &url).unwrap();
9045
    assert_eq!(c.default_remote(), "origin");
9046
}
9047
9048
/// oxygen#57: a clone from a relative local path records the remote as an
9049
/// absolute path, so fetch still finds it from inside the clone.
9050
#[test]
9051
fn a_clone_from_a_relative_path_records_it_absolute() {
9052
    hermetic();
9053
    let dir = tempfile::tempdir().unwrap();
9054
    let root = dir.path();
9055
    Repo::init(&root.join("origin")).unwrap();
9056
    let rel = crate::protocol::stored_url("relative/repo");
9057
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
9058
    assert_eq!(
9059
        crate::protocol::stored_url("https://hub.example/o/n"),
9060
        "https://hub.example/o/n"
9061
    );
9062
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
9063
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
9064
    // A bucket is kept as written: it is not a path.
9065
    assert_eq!(
9066
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
9067
        "s3://bucket/prefix?profile=p"
9068
    );
9069
    let url = root.join("origin").to_string_lossy().to_string();
9070
    let b = Repo::clone(&url, &root.join("b")).unwrap();
9071
    assert_eq!(b.config.remotes["origin"], url);
9072
    b.fetch("origin").unwrap();
9073
}
9074
9075
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
9076
/// and gets its subrepos at their pins from this workspace's copies, with
9077
/// their remotes pointing where the subrepos come from.
9078
#[test]
9079
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
9080
    hermetic();
9081
    let dir = tempfile::tempdir().unwrap();
9082
    let root = dir.path();
9083
    Repo::init(&root.join("lib-origin")).unwrap();
9084
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9085
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9086
        .unwrap()
9087
        .with_home(root.join("home"));
9088
    write(&root.join("lib"), "lib.txt", b"v1\n");
9089
    let l1 = lib.commit("lib v1", &[]).unwrap();
9090
    assert!(lib.push("origin", false).unwrap()[0].ok);
9091
9092
    let app_dir = root.join("app");
9093
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
9094
    write(&app_dir, "main.txt", b"app\n");
9095
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9096
    app.commit("app with lib", &[]).unwrap();
9097
    // A second bookmark, and the main workspace on another.
9098
    app.bookmark_create("develop", None).unwrap();
9099
    app.bookmark_create("feature", None).unwrap();
9100
    let mut app = app;
9101
    app.bookmark_switch("feature", false).unwrap();
9102
    assert_eq!(app.config.bookmark, "feature");
9103
9104
    // The library's origin goes away: the subrepo must come from here.
9105
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
9106
    let heads = app.resolve_heads("develop").unwrap();
9107
    let ws = app
9108
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
9109
        .unwrap();
9110
    assert_eq!(
9111
        ws.config.bookmark, "develop",
9112
        "the new workspace is on develop"
9113
    );
9114
    assert_eq!(
9115
        app.config.bookmark, "feature",
9116
        "and this one stays on its own"
9117
    );
9118
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
9119
    assert_eq!(
9120
        sub.config.remotes["origin"], lib_url,
9121
        "its origin is the subrepo's URL"
9122
    );
9123
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
9124
    assert_eq!(
9125
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
9126
        b"v1\n"
9127
    );
9128
}
9129
9130
/// Revsets (docs/revset_query_language.md): symbols, relations, set
9131
/// operators and the predicates, over a small graph with two heads and
9132
/// a rename.
9133
#[test]
9134
fn revsets_select_changes_by_relation_author_text_date_and_path() {
9135
    hermetic();
9136
    let dir = tempfile::tempdir().unwrap();
9137
    let root = dir.path();
9138
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
9139
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
9140
        .unwrap();
9141
    write(root, "src/a.rs", b"one\n");
9142
    let a = repo.commit("first: add a", &[]).unwrap();
9143
    write(root, "src/a.rs", b"one\ntwo\n");
9144
    let b = repo.commit("second: grow a", &[]).unwrap();
9145
    // A second head, independent of b: a new file on top of a.
9146
    repo.checkout(&[a], false, "checkout a").unwrap();
9147
    write(root, "docs/notes.md", b"notes\n");
9148
    let c = repo.commit("third: notes", &[]).unwrap();
9149
    // Back to both heads, then rename a.rs: the node keeps its identity.
9150
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
9151
        .unwrap();
9152
    fs::remove_file(root.join("src/a.rs")).unwrap();
9153
    write(root, "src/z.rs", b"one\ntwo\n");
9154
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
9155
    let wc = repo.working_copy().unwrap().0;
9156
    // A saved revset is checked when set.
9157
    repo.set_user_config("revset.mine", "author(me) & ::main")
9158
        .unwrap();
9159
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
9160
    let set = |src: &str| -> Vec<ChangeHash> {
9161
        let mut v = repo.revset(src).unwrap().hashes;
9162
        v.sort();
9163
        v
9164
    };
9165
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
9166
        let mut v = hs.to_vec();
9167
        v.sort();
9168
        v
9169
    };
9170
9171
    // Changes commute: a new file depends on nothing and the rename on the
9172
    // file's creation, so the graph is a, b->a, d->a, c, and the working
9173
    // copy on the three heads b, c, d.
9174
    let heads = sorted(&repo.bookmark_heads().unwrap());
9175
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
9176
    assert!(heads.contains(&d) && heads.contains(&c));
9177
    // Symbols and closures.
9178
    assert_eq!(set("main"), heads);
9179
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
9180
    assert_eq!(set("@"), vec![wc]);
9181
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
9182
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
9183
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
9184
    assert_eq!(
9185
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
9186
        sorted(&[a, b])
9187
    );
9188
    // Ranges: what main has beyond b, and `..` forms.
9189
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
9190
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
9191
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
9192
    // Operators and precedence: ~ binds tighter than &, & than |.
9193
    assert_eq!(
9194
        set(&format!("::main ~ #{}", d.short(12))),
9195
        sorted(&[a, b, c])
9196
    );
9197
    assert_eq!(
9198
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
9199
        sorted(&[b, c])
9200
    );
9201
    assert_eq!(set("all() ~ ::main"), vec![wc]);
9202
    // Relations.
9203
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
9204
    head_deps.sort();
9205
    head_deps.dedup();
9206
    assert_eq!(set("deps(main)"), head_deps);
9207
    let on_a: Vec<ChangeHash> = [b, c, d]
9208
        .into_iter()
9209
        .filter(|h| meta(h).deps.contains(&a))
9210
        .collect();
9211
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
9212
    assert_eq!(set("heads(::main)"), heads);
9213
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
9214
    assert_eq!(
9215
        set(&format!(
9216
            "heads(#{} | #{} | #{})",
9217
            a.short(12),
9218
            b.short(12),
9219
            c.short(12)
9220
        )),
9221
        sorted(&[b, c])
9222
    );
9223
    assert_eq!(set("latest(::main, 1)"), vec![d]);
9224
    assert_eq!(set("kind(working-copy)"), vec![wc]);
9225
    assert_eq!(set("none()"), vec![]);
9226
    // Predicates: author by name, email, key prefix and `me`.
9227
    let key = repo.config.author_key.unwrap();
9228
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
9229
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
9230
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
9231
    assert_eq!(set("author(me) & ::main").len(), 4);
9232
    assert_eq!(set("author(nobody)"), vec![]);
9233
    assert_eq!(set("description(notes)"), vec![c]);
9234
    assert_eq!(set("description(\"rename a\")"), vec![d]);
9235
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
9236
    assert_eq!(set("date(..2000-01-01)"), vec![]);
9237
    // touches follows the node through the rename, in the current state.
9238
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
9239
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
9240
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
9241
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
9242
    // Newest first in the result order.
9243
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
9244
    // The saved revset, and errors that say what is wrong.
9245
    assert_eq!(set("mine()").len(), 4);
9246
    let e = repo.revset("nosuch()").unwrap_err().to_string();
9247
    assert!(e.contains("unknown function nosuch()"), "{e}");
9248
    let e = repo.revset("main &").unwrap_err().to_string();
9249
    assert!(e.contains("at character"), "{e}");
9250
    let e = repo.revset("zzzz").unwrap_err().to_string();
9251
    assert!(e.contains("no change matches"), "{e}");
9252
    let e = repo
9253
        .revset_with_budget("::main", std::time::Duration::ZERO)
9254
        .unwrap_err()
9255
        .to_string();
9256
    assert!(e.contains("budget"), "{e}");
9257
    // The log entries carry the bookmark's heads and the working copy.
9258
    let entries = repo.log_revset("::@").unwrap();
9259
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
9260
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
9261
    // push); then a signed change, a tag, and a revocation.
9262
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
9263
    assert_eq!(set("signed_by(me)"), vec![]);
9264
    repo.sign_change(&d).unwrap();
9265
    assert_eq!(set("signed_by(me)"), vec![d]);
9266
    assert_eq!(set("signed_by([email protected])"), vec![d]);
9267
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
9268
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
9269
    assert_eq!(set("delegated()"), vec![]);
9270
    assert_eq!(set("revoked()"), vec![]);
9271
    assert_eq!(set("attested(tag)"), vec![]);
9272
    repo.tag_create("v1", &[b], "first").unwrap();
9273
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
9274
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
9275
    assert_eq!(set("attested(receipt)"), vec![]);
9276
    assert_eq!(set("built(test)"), vec![]);
9277
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
9278
    assert!(e.contains("tag, receipt or ref"), "{e}");
9279
    repo.revoke_identity(&key, "test").unwrap();
9280
    assert_eq!(set("revoked()"), vec![d]);
9281
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
9282
    // independent(X, IN): what could ship without X. c and d neither
9283
    // depend on b nor are depended on by it; a is below, the working copy
9284
    // above.
9285
    assert_eq!(
9286
        set(&format!("independent(#{}, ::@)", b.short(12))),
9287
        sorted(&[c, d])
9288
    );
9289
    assert_eq!(
9290
        set(&format!("independent(#{}, ::main)", a.short(12))),
9291
        vec![c]
9292
    );
9293
    // conflicts(S): nothing conflicts yet; then two edits of one line.
9294
    assert_eq!(set("conflicts()"), vec![]);
9295
    assert_eq!(set("conflicts(main)"), vec![]);
9296
    // (The saved revset above edited the user config under the root:
9297
    // discard it.)
9298
    repo.checkout(&[a], true, "checkout a").unwrap();
9299
    write(root, "src/a.rs", b"one\nTWO\n");
9300
    let e = repo
9301
        .commit("fifth: the other edit of line two", &[])
9302
        .unwrap();
9303
    repo.checkout(&repo.bookmark_heads().unwrap(), true, "checkout main")
9304
        .unwrap();
9305
    let conflicted = repo.revset("conflicts()").unwrap().hashes;
9306
    assert!(
9307
        conflicted.contains(&e) && conflicted.contains(&b),
9308
        "{conflicted:?} should hold b and e"
9309
    );
9310
    assert!(!conflicted.contains(&c));
9311
    assert_eq!(set("conflicts() & author(nobody)"), vec![]);
9312
}
9313
9314
#[test]
9315
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
9316
    let dir = tempfile::tempdir().unwrap();
9317
    let root = dir.path();
9318
    let home = root.join("home");
9319
    // Ada's identity lives in the user file; repository `a` pins the same
9320
    // key in its own file, repository `b` names none.
9321
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
9322
    let (key, _) = a
9323
        .create_identity("Ada", "[email protected]", IdentityScope::User)
9324
        .unwrap();
9325
    a.config.set("author.key", &key.to_hex()).unwrap();
9326
    a.save_config().unwrap();
9327
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
9328
    let r = a
9329
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
9330
        .unwrap();
9331
    assert_eq!(
9332
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
9333
        r.new.to_hex(),
9334
        "the user file follows"
9335
    );
9336
    assert_eq!(
9337
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
9338
        r.new.to_hex(),
9339
        "the pinning repository follows"
9340
    );
9341
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
9342
    assert_eq!(
9343
        b.config.author_key,
9344
        Some(r.new),
9345
        "a checkout without a pin follows the user file"
9346
    );
9347
    // A repository-scoped identity leaves the user file alone.
9348
    let other_home = root.join("home2");
9349
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
9350
    let (ck, _) = c
9351
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
9352
        .unwrap();
9353
    assert!(!other_home.join("config.toml").exists());
9354
    let r2 = c.rotate_identity().unwrap();
9355
    assert_ne!(r2.new, ck);
9356
    assert_eq!(
9357
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
9358
        r2.new.to_hex()
9359
    );
9360
    assert!(
9361
        !other_home.join("config.toml").exists(),
9362
        "a repository-scoped identity stays repository-scoped"
9363
    );
9364
    // Several delegates in one rotation; a repeat is refused.
9365
    let (d1, d2) = (
9366
        SecretKey::generate().identity("D1", "d1@x", 1),
9367
        SecretKey::generate().identity("D2", "d2@x", 1),
9368
    );
9369
    let r3 = c
9370
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
9371
        .unwrap();
9372
    assert_eq!(r3.identity.delegates.len(), 2);
9373
    assert!(c
9374
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
9375
        .is_err());
9376
}
9377
9378
/// Two unrelated histories that both add the same file, joined by two
9379
/// independent merges on two branches, then those branches merged: Git
9380
/// merges identical additions cleanly, and the import must too (#71,
9381
/// found in VS Code's history).
9382
#[test]
9383
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
9384
    // Batches of one: every merge renders apart from the state, where a
9385
    // file whose graph the state had built came out empty (#71).
9386
    crate::repo::git::set_merge_batch_for_tests(Some(1));
9387
    hermetic();
9388
    if std::process::Command::new("git")
9389
        .arg("--version")
9390
        .output()
9391
        .is_err()
9392
    {
9393
        eprintln!("git not installed; skipping");
9394
        return;
9395
    }
9396
    let dir = tempfile::tempdir().unwrap();
9397
    let root = dir.path();
9398
    let g = root.join("src.git");
9399
    fs::create_dir_all(&g).unwrap();
9400
    let git = |args: &[&str]| -> String {
9401
        let out = std::process::Command::new("git")
9402
            .arg("-C")
9403
            .arg(&g)
9404
            .args([
9405
                "-c",
9406
                "user.name=Grace",
9407
                "-c",
9408
                "[email protected]",
9409
                "-c",
9410
                "commit.gpgsign=false",
9411
            ])
9412
            .args(args)
9413
            .output()
9414
            .unwrap();
9415
        assert!(
9416
            out.status.success(),
9417
            "git {args:?}: {}",
9418
            String::from_utf8_lossy(&out.stderr)
9419
        );
9420
        String::from_utf8_lossy(&out.stdout).trim().to_string()
9421
    };
9422
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
9423
    // History A: main.
9424
    git(&["init", "-q", "-b", "main"]);
9425
    write(&g, "gulpfile.js", text);
9426
    write(&g, "a.txt", b"a\n");
9427
    git(&["add", "."]);
9428
    git(&["commit", "-q", "-m", "A root"]);
9429
    // History B: an unrelated root adding the same file, identical.
9430
    git(&["checkout", "-q", "--orphan", "fork"]);
9431
    git(&["rm", "-q", "-r", "--cached", "."]);
9432
    for f in ["gulpfile.js", "a.txt"] {
9433
        let _ = fs::remove_file(g.join(f));
9434
    }
9435
    write(&g, "gulpfile.js", text);
9436
    write(&g, "b.txt", b"b\n");
9437
    git(&["add", "."]);
9438
    git(&["commit", "-q", "-m", "B root"]);
9439
    // Two branches from main, each joining B on its own.
9440
    git(&["checkout", "-q", "-b", "one", "main"]);
9441
    git(&[
9442
        "merge",
9443
        "-q",
9444
        "--no-ff",
9445
        "--allow-unrelated-histories",
9446
        "-m",
9447
        "join on one",
9448
        "fork",
9449
    ]);
9450
    git(&["checkout", "-q", "-b", "two", "main"]);
9451
    write(&g, "a.txt", b"a\ntwo\n");
9452
    git(&["commit", "-q", "-am", "work on two"]);
9453
    git(&[
9454
        "merge",
9455
        "-q",
9456
        "--no-ff",
9457
        "--allow-unrelated-histories",
9458
        "-m",
9459
        "join on two",
9460
        "fork",
9461
    ]);
9462
    // Then the two joins meet, and the file is reformatted after.
9463
    git(&["checkout", "-q", "main"]);
9464
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
9465
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
9466
    write(
9467
        &g,
9468
        "gulpfile.js",
9469
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
9470
    );
9471
    git(&["commit", "-q", "-am", "after"]);
9472
9473
    let dest = root.join("dest");
9474
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
9475
    repo.import_git(&g, "main").unwrap();
9476
    let v = repo.verify_git_import(&g, "main").unwrap();
9477
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9478
    assert_eq!(
9479
        fs::read(dest.join("gulpfile.js")).unwrap(),
9480
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
9481
    );
9482
}
9483
9484
/// As above, but the two joins keep different copies (each branch had a
9485
/// different version when it joined), and later work edits each copy:
9486
/// the shape of VS Code's c67ef57cda90 (#71).
9487
#[test]
9488
fn git_import_joins_where_each_join_kept_a_different_copy() {
9489
    // Batches of one: every merge renders apart from the state, where a
9490
    // file whose graph the state had built came out empty (#71).
9491
    crate::repo::git::set_merge_batch_for_tests(Some(1));
9492
    hermetic();
9493
    if std::process::Command::new("git")
9494
        .arg("--version")
9495
        .output()
9496
        .is_err()
9497
    {
9498
        eprintln!("git not installed; skipping");
9499
        return;
9500
    }
9501
    let dir = tempfile::tempdir().unwrap();
9502
    let root = dir.path();
9503
    let g = root.join("src.git");
9504
    fs::create_dir_all(&g).unwrap();
9505
    let run = |args: &[&str]| {
9506
        std::process::Command::new("git")
9507
            .arg("-C")
9508
            .arg(&g)
9509
            .args([
9510
                "-c",
9511
                "user.name=Grace",
9512
                "-c",
9513
                "[email protected]",
9514
                "-c",
9515
                "commit.gpgsign=false",
9516
            ])
9517
            .args(args)
9518
            .output()
9519
            .unwrap()
9520
    };
9521
    let git = |args: &[&str]| -> String {
9522
        let out = run(args);
9523
        assert!(
9524
            out.status.success(),
9525
            "git {args:?}: {}",
9526
            String::from_utf8_lossy(&out.stderr)
9527
        );
9528
        String::from_utf8_lossy(&out.stdout).trim().to_string()
9529
    };
9530
    git(&["init", "-q", "-b", "main"]);
9531
    write(
9532
        &g,
9533
        "gulpfile.js",
9534
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
9535
    );
9536
    git(&["add", "."]);
9537
    git(&["commit", "-q", "-m", "A root"]);
9538
    write(
9539
        &g,
9540
        "gulpfile.js",
9541
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
9542
    );
9543
    git(&["commit", "-q", "-am", "whitespace"]);
9544
    git(&["checkout", "-q", "--orphan", "fork"]);
9545
    git(&["rm", "-q", "-r", "--cached", "."]);
9546
    let _ = fs::remove_file(g.join("gulpfile.js"));
9547
    write(
9548
        &g,
9549
        "gulpfile.js",
9550
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
9551
    );
9552
    git(&["add", "."]);
9553
    git(&["commit", "-q", "-m", "B root"]);
9554
    // Branch one joins B keeping main's copy; branch two keeps B's.
9555
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
9556
        git(&["checkout", "-q", "-b", branch, "main"]);
9557
        let _ = run(&[
9558
            "merge",
9559
            "-q",
9560
            "--no-ff",
9561
            "--allow-unrelated-histories",
9562
            "-m",
9563
            "join",
9564
            "fork",
9565
        ]);
9566
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
9567
        git(&["add", "gulpfile.js"]);
9568
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
9569
    }
9570
    // Each branch then edits its copy.
9571
    git(&["checkout", "-q", "one"]);
9572
    write(
9573
        &g,
9574
        "gulpfile.js",
9575
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
9576
    );
9577
    git(&["commit", "-q", "-am", "tslint on one"]);
9578
    git(&["checkout", "-q", "two"]);
9579
    write(
9580
        &g,
9581
        "gulpfile.js",
9582
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
9583
    );
9584
    write(&g, "extra.txt", b"x\n");
9585
    write(&g, "more.txt", b"m\n");
9586
    git(&["add", "."]);
9587
    git(&["commit", "-q", "-am", "fmt on two"]);
9588
    // They meet: resolved by hand.
9589
    git(&["checkout", "-q", "one"]);
9590
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
9591
    write(
9592
        &g,
9593
        "gulpfile.js",
9594
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
9595
    );
9596
    git(&["add", "gulpfile.js"]);
9597
    git(&["commit", "-q", "-m", "merge two into one"]);
9598
9599
    let dest = root.join("dest");
9600
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
9601
    repo.import_git(&g, "one").unwrap();
9602
    let v = repo.verify_git_import(&g, "one").unwrap();
9603
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9604
}
9605
9606
/// oxygen#68: on a store that is not this disk's directory, the operation
9607
/// head is the store's reference record, moved by compare-and-swap. Two
9608
/// handles recording from the same head both get through, merged; a swap
9609
/// from a stale version is refused; a second repository cannot start on a
9610
/// store that already holds one.
9611
#[test]
9612
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
9613
    use crate::strata::{MemoryStore, Store as _};
9614
    let backend = std::sync::Arc::new(MemoryStore::new());
9615
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
9616
    let dir = tempfile::tempdir().unwrap();
9617
    let a = Repo::init(dir.path()).unwrap();
9618
    assert!(
9619
        !dir.path().join(".oxy/ops/head").exists(),
9620
        "the head is not a file"
9621
    );
9622
    let (h0, op0) = a.head_op().unwrap();
9623
    let record = backend
9624
        .read_ref(HEAD_RECORD)
9625
        .unwrap()
9626
        .expect("the head is the store's record");
9627
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
9628
9629
    let b = Repo::open(dir.path()).unwrap();
9630
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
9631
    let mut va = op0.view.clone();
9632
    va.bookmarks.insert("from-a".into(), state);
9633
    let mut vb = op0.view.clone();
9634
    vb.bookmarks.insert("from-b".into(), state);
9635
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
9636
    assert_eq!(b.head_ref().unwrap(), rb);
9637
    // a recorded from h0 too: the head moved, so the two are merged.
9638
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
9639
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
9640
    assert_eq!(head, ra);
9641
    assert!(
9642
        op.command.ends_with("(merged with a concurrent operation)"),
9643
        "{}",
9644
        op.command
9645
    );
9646
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
9647
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
9648
9649
    // A swap from a version that is no longer current moves nothing.
9650
    let (h, v) = a.read_head().unwrap();
9651
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
9652
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
9653
    a.refresh().unwrap();
9654
    assert_eq!(a.head_ref().unwrap(), rb);
9655
9656
    let other = tempfile::tempdir().unwrap();
9657
    let err = Repo::init(other.path())
9658
        .err()
9659
        .expect("the store already holds a log")
9660
        .to_string();
9661
    assert!(
9662
        err.contains("already holds a repository's operation log"),
9663
        "{err}"
9664
    );
9665
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
9666
}
9667
9668
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
9669
/// objects and operation head there, with `.oxy/cache` in front: it works
9670
/// as one on disk does, reopens, and survives losing its cache.
9671
#[test]
9672
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
9673
    hermetic();
9674
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
9675
        return;
9676
    }
9677
    let dir = tempfile::tempdir().unwrap();
9678
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
9679
    let url = format!("dir://{}", bucket.display());
9680
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
9681
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
9682
    write(&root, "a.txt", b"one\n");
9683
    let h1 = repo.commit("First", &[]).unwrap();
9684
    write(&root, "a.txt", b"one\ntwo\n");
9685
    let h2 = repo.commit("Second", &[]).unwrap();
9686
    assert!(
9687
        !root.join(".oxy/ops/head").exists(),
9688
        "the head is in the store"
9689
    );
9690
    assert!(bucket.join("ops/head").is_file());
9691
    assert!(root.join(".oxy/cache").is_dir());
9692
    drop(repo);
9693
9694
    // Reopened, and again with no cache at all: everything comes from the store.
9695
    for drop_cache in [false, true] {
9696
        if drop_cache {
9697
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
9698
        }
9699
        let repo = Repo::open(&root).unwrap();
9700
        let log: Vec<String> = repo
9701
            .op_log()
9702
            .unwrap()
9703
            .into_iter()
9704
            .map(|(_, op)| op.command)
9705
            .collect();
9706
        assert!(log.len() >= 3, "{log:?}");
9707
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
9708
        let heads = repo
9709
            .store()
9710
            .get_state(&repo.view().unwrap().bookmarks["main"])
9711
            .unwrap()
9712
            .heads;
9713
        assert_eq!(heads, vec![h2]);
9714
        assert_eq!(
9715
            repo.load_state(&heads).unwrap().materialize().files.len(),
9716
            1
9717
        );
9718
    }
9719
9720
    // A second repository cannot start on the same store.
9721
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
9722
        .err()
9723
        .unwrap()
9724
        .to_string();
9725
    assert!(
9726
        err.contains("already holds a repository's operation log"),
9727
        "{err}"
9728
    );
9729
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
9730
        .err()
9731
        .unwrap()
9732
        .to_string();
9733
    assert!(err.contains("cannot open that kind of store"), "{err}");
9734
}
9735
9736
/// oxygen#75: the prompt's quick check agrees with status in a repository
9737
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
9738
/// another state, clean again once that pin is committed. (It compared the
9739
/// subrepo's directory as if it were a file, so it was always dirty.)
9740
#[test]
9741
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
9742
    hermetic();
9743
    let dir = tempfile::tempdir().unwrap();
9744
    let root = dir.path();
9745
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9746
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9747
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9748
        .unwrap()
9749
        .with_home(root.join("home"));
9750
    write(&root.join("lib"), "lib.txt", b"v1\n");
9751
    lib.commit("lib v1", &[]).unwrap();
9752
    assert!(lib.push("origin", false).unwrap()[0].ok);
9753
    let app_dir = root.join("app");
9754
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
9755
    write(&app_dir, "main.txt", b"app\n");
9756
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9757
    app.commit("app with lib", &[]).unwrap();
9758
    // Out of the racy window, so the stat-only path decides.
9759
    std::thread::sleep(std::time::Duration::from_millis(2100));
9760
    let reopen = || Repo::open(&app_dir).unwrap();
9761
    assert_eq!(
9762
        reopen().quick_dirty().unwrap(),
9763
        Some(false),
9764
        "clean, as status says"
9765
    );
9766
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
9767
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
9768
    nested.commit("lib v2", &[]).unwrap();
9769
    assert_eq!(
9770
        reopen().quick_dirty().unwrap(),
9771
        Some(true),
9772
        "the subrepo moved"
9773
    );
9774
    reopen().commit("pin lib v2", &[]).unwrap();
9775
    std::thread::sleep(std::time::Duration::from_millis(2100));
9776
    assert_eq!(
9777
        reopen().quick_dirty().unwrap(),
9778
        Some(false),
9779
        "the new pin is committed"
9780
    );
9781
}
9782
9783
#[test]
9784
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
9785
    // oxygen#72: a .oxymodules section with no subrepo behind it.
9786
    hermetic();
9787
    let dir = tempfile::tempdir().unwrap();
9788
    let root = dir.path();
9789
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9790
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9791
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9792
        .unwrap()
9793
        .with_home(root.join("home"));
9794
    write(&root.join("lib"), "lib.txt", b"v1\n");
9795
    lib.commit("lib v1", &[]).unwrap();
9796
    assert!(lib.push("origin", false).unwrap()[0].ok);
9797
    let app_dir = root.join("app");
9798
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
9799
    write(
9800
        &app_dir,
9801
        ".oxymodules",
9802
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
9803
    );
9804
    let unpinned = app.unpinned_modules().unwrap();
9805
    assert_eq!(unpinned.len(), 1);
9806
    assert_eq!(unpinned[0].0, "libs/lib");
9807
    assert_eq!(unpinned[0].1.url, lib_url);
9808
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
9809
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9810
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
9811
}
9812
9813
#[test]
9814
fn the_bookmark_revset_function_names_only_bookmarks() {
9815
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
9816
    hermetic();
9817
    let dir = tempfile::tempdir().unwrap();
9818
    let repo = Repo::init(dir.path()).unwrap();
9819
    write(dir.path(), "a.txt", b"a\n");
9820
    let a = repo.commit("A", &[]).unwrap();
9821
    write(dir.path(), "b.txt", b"b\n");
9822
    let b = repo.commit("B", &[]).unwrap();
9823
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
9824
    heads.sort();
9825
    let mut want = repo.bookmark_heads().unwrap();
9826
    want.sort();
9827
    assert_eq!(heads, want);
9828
    assert!(heads.contains(&b));
9829
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
9830
    // A change prefix is a symbol, not a bookmark.
9831
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
9832
    assert!(repo.revset(&prefix).is_ok());
9833
    let e = repo
9834
        .revset(&format!("bookmark({prefix})"))
9835
        .unwrap_err()
9836
        .to_string();
9837
    assert!(e.contains("no such bookmark"), "{e}");
9838
}
9839
9840
/// oxygen#140: a replace conflict is settled from the working copy, as
9841
/// `oxy resolve PATH` does: the path's content on disk becomes the
9842
/// resolution, and the commit that records it is a Resolution.
9843
#[test]
9844
fn a_replace_conflict_is_settled_from_the_working_copy() {
9845
    hermetic();
9846
    let dir = tempfile::tempdir().unwrap();
9847
    let root = dir.path();
9848
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
9849
    let blob = |n: u8| {
9850
        let mut v = vec![0u8; 64];
9851
        v[1] = n;
9852
        v
9853
    };
9854
    write(root, "img.bin", &blob(1));
9855
    write(root, "a.txt", b"a\n");
9856
    repo.commit("add img", &[]).unwrap();
9857
    repo.bookmark_create("other", None).unwrap();
9858
    write(root, "img.bin", &blob(2));
9859
    repo.commit("img two", &[]).unwrap();
9860
    repo.bookmark_switch("other", false).unwrap();
9861
    write(root, "img.bin", &blob(3));
9862
    repo.commit("img three", &[]).unwrap();
9863
    repo.bookmark_switch("main", false).unwrap();
9864
    repo.merge("other").unwrap();
9865
    // Without a choice, nothing the working copy holds settles it, and
9866
    // other work cannot be committed past it.
9867
    write(root, "img.bin", &blob(9));
9868
    write(root, "a.txt", b"a\nmore\n");
9869
    assert!(
9870
        repo.commit("edit a", &[]).is_err(),
9871
        "refused while conflicted"
9872
    );
9873
    let snap = repo.snapshot("oxy resolve").unwrap();
9874
    assert!(
9875
        repo.choose_resolutions(&snap.base_snapshot, &["a.txt".to_string()])
9876
            .is_err(),
9877
        "a.txt has no replace conflict"
9878
    );
9879
    repo.choose_resolutions(&snap.base_snapshot, &["img.bin".to_string()])
9880
        .unwrap();
9881
    let snap = repo.snapshot("oxy resolve").unwrap();
9882
    assert!(snap
9883
        .statuses
9884
        .iter()
9885
        .any(|s| s.path == "img.bin" && s.status == ChangeStatus::Resolved));
9886
    let c = repo.commit("settle img", &[]).unwrap();
9887
    assert_eq!(
9888
        repo.store().get_change(&c).unwrap().kind,
9889
        ChangeKind::Resolution
9890
    );
9891
    let after = repo
9892
        .load_state(&repo.bookmark_heads().unwrap())
9893
        .unwrap()
9894
        .materialize();
9895
    assert!(!after.is_conflicted());
9896
    assert_eq!(
9897
        after.files["img.bin"].content,
9898
        FileContent::Opaque {
9899
            blobs: vec![Repo::blob_ref(&blob(9))]
9900
        }
9901
    );
9902
    assert!(
9903
        matches!(&after.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nmore\n")
9904
    );
9905
    // Settled: the choice is forgotten, and the working copy is clean.
9906
    let snap = repo.snapshot("status").unwrap();
9907
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
9908
    assert!(repo.resolutions().unwrap().is_empty());
9909
}
9910
9911
/// oxygen#140: the same for a subrepo pin moved two ways at once.
9912
#[test]
9913
fn a_pin_conflict_is_settled_from_the_working_copy() {
9914
    hermetic();
9915
    let dir = tempfile::tempdir().unwrap();
9916
    let root = dir.path();
9917
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9918
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9919
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9920
        .unwrap()
9921
        .with_home(root.join("home"));
9922
    write(&root.join("lib"), "lib.txt", b"v1\n");
9923
    lib.commit("lib v1", &[]).unwrap();
9924
    assert!(lib.push("origin", false).unwrap()[0].ok);
9925
    let app_dir = root.join("app");
9926
    let mut app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
9927
    write(&app_dir, "main.txt", b"app\n");
9928
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9929
    app.commit("pin v1", &[]).unwrap();
9930
    let nested = Repo::open(&app_dir.join("libs/lib"))
9931
        .unwrap()
9932
        .with_home(root.join("home"));
9933
    fn pin(app: &Repo, nested: &Repo, text: &[u8], message: &str) {
9934
        write(nested.root(), "lib.txt", text);
9935
        nested.commit(message, &[]).unwrap();
9936
        app.commit(&format!("pin {message}"), &[]).unwrap();
9937
    }
9938
    app.bookmark_create("other", None).unwrap();
9939
    pin(&app, &nested, b"v2\n", "v2");
9940
    app.bookmark_switch("other", false).unwrap();
9941
    pin(&app, &nested, b"v3\n", "v3");
9942
    app.bookmark_switch("main", false).unwrap();
9943
    app.merge("other").unwrap();
9944
    let merged = app
9945
        .load_state(&app.bookmark_heads().unwrap())
9946
        .unwrap()
9947
        .materialize();
9948
    assert!(
9949
        matches!(&merged.files["libs/lib"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
9950
        "a pin conflict"
9951
    );
9952
    // The nested repository moves on once more; that pin is the choice.
9953
    write(&app_dir.join("libs/lib"), "lib.txt", b"v4\n");
9954
    nested.commit("v4", &[]).unwrap();
9955
    let snap = app.snapshot("oxy resolve").unwrap();
9956
    app.choose_resolutions(&snap.base_snapshot, &["libs/lib".to_string()])
9957
        .unwrap();
9958
    let c = app.commit("settle the pin", &[]).unwrap();
9959
    assert_eq!(
9960
        app.store().get_change(&c).unwrap().kind,
9961
        ChangeKind::Resolution
9962
    );
9963
    let after = app
9964
        .load_state(&app.bookmark_heads().unwrap())
9965
        .unwrap()
9966
        .materialize();
9967
    assert!(!after.is_conflicted());
9968
    assert!(app.snapshot("status").unwrap().statuses.is_empty());
9969
}
9970
9971
#[test]
9972
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
9973
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
9974
    // pinning the subrepo, and the nested repository on disk at that pin.
9975
    hermetic();
9976
    let dir = tempfile::tempdir().unwrap();
9977
    let root = dir.path();
9978
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9979
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9980
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9981
        .unwrap()
9982
        .with_home(root.join("home"));
9983
    write(&root.join("lib"), "lib.txt", b"v1\n");
9984
    lib.commit("lib v1", &[]).unwrap();
9985
    assert!(lib.push("origin", false).unwrap()[0].ok);
9986
    let app_dir = root.join("app");
9987
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
9988
    write(&app_dir, "main.txt", b"app\n");
9989
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9990
    // The stale state: registered in .oxymodules, never pinned.
9991
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
9992
    app.commit("initial", &[]).unwrap();
9993
    let stale = app.bookmark_heads().unwrap();
9994
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
9995
    app.commit("pin lib", &[]).unwrap();
9996
    let newer = app.bookmark_heads().unwrap();
9997
    app.checkout(&stale, false, "test").unwrap();
9998
    write(&app_dir, "notes.txt", b"mine\n");
9999
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
10000
    assert_eq!(carried, vec!["notes.txt".to_string()]);
10001
    assert!(app_dir.join("notes.txt").exists());
10002
}
10003
10004
/// oxygen#142: a new bookmark made from main sends what main lacks, not
10005
/// its whole history again.
10006
#[test]
10007
fn a_new_bookmark_sends_only_what_the_remote_lacks() {
10008
    hermetic();
10009
    let dir = tempfile::tempdir().unwrap();
10010
    let root = dir.path();
10011
    let _origin = Repo::init(&root.join("origin")).unwrap();
10012
    let url = root.join("origin").to_string_lossy().to_string();
10013
    let mut one = Repo::clone(&url, &root.join("one"))
10014
        .unwrap()
10015
        .with_home(root.join("home"));
10016
    for n in 0..5 {
10017
        write(&root.join("one"), "a.txt", format!("{n}\n").as_bytes());
10018
        one.commit(&format!("main {n}"), &[]).unwrap();
10019
    }
10020
    assert!(one.push("origin", false).unwrap()[0].ok);
10021
    one.bookmark_create("feature", None).unwrap();
10022
    one.bookmark_switch("feature", false).unwrap();
10023
    write(&root.join("one"), "b.txt", b"feature\n");
10024
    let added = one.commit("feature", &[]).unwrap();
10025
    let heads = one.bookmark_heads().unwrap();
10026
    let refs = one
10027
        .open_named_remote("origin")
10028
        .unwrap()
10029
        .refs()
10030
        .unwrap()
10031
        .refs;
10032
    assert!(
10033
        refs.iter().all(|r| r.name != "feature"),
10034
        "new to the remote"
10035
    );
10036
    let sent = one
10037
        .negotiate(&one.remote_holds(&refs, &[]), &heads)
10038
        .unwrap();
10039
    assert_eq!(sent, vec![added], "only the change main lacks");
10040
    assert!(one.push_bookmark("origin", "feature", false).unwrap()[0].ok);
10041
    let two = Repo::clone(&url, &root.join("two")).unwrap();
10042
    assert!(two.store().has(&added));
10043
}
10044
10045
#[test]
10046
fn a_bookmark_only_behind_its_remote_catches_up() {
10047
    // oxygen#74: switch takes the remote's state rather than a stale one.
10048
    hermetic();
10049
    let dir = tempfile::tempdir().unwrap();
10050
    let root = dir.path();
10051
    let _origin = Repo::init(&root.join("origin")).unwrap();
10052
    let url = root.join("origin").to_string_lossy().to_string();
10053
    let one = Repo::clone(&url, &root.join("one"))
10054
        .unwrap()
10055
        .with_home(root.join("home"));
10056
    write(&root.join("one"), "a.txt", b"a\n");
10057
    one.commit("A", &[]).unwrap();
10058
    assert!(one.push("origin", false).unwrap()[0].ok);
10059
    let two = Repo::clone(&url, &root.join("two"))
10060
        .unwrap()
10061
        .with_home(root.join("home"));
10062
    write(&root.join("two"), "b.txt", b"b\n");
10063
    two.commit("B", &[]).unwrap();
10064
    assert!(two.push("origin", false).unwrap()[0].ok);
10065
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
10066
    one.fetch("origin").unwrap();
10067
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
10068
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
10069
    // Local work the remote lacks: left alone.
10070
    write(&root.join("one"), "c.txt", b"c\n");
10071
    one.commit("C", &[]).unwrap();
10072
    write(&root.join("two"), "d.txt", b"d\n");
10073
    two.commit("D", &[]).unwrap();
10074
    assert!(two.push("origin", false).unwrap()[0].ok);
10075
    one.fetch("origin").unwrap();
10076
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
10077
}
10078
10079
#[test]
10080
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
10081
    // oxygen#83: remotes earth and gcs, origin removed.
10082
    hermetic();
10083
    let dir = tempfile::tempdir().unwrap();
10084
    let root = dir.path();
10085
    let _up = Repo::init(&root.join("up")).unwrap();
10086
    let url = root.join("up").to_string_lossy().to_string();
10087
    let other = Repo::clone(&url, &root.join("other"))
10088
        .unwrap()
10089
        .with_home(root.join("home"));
10090
    write(&root.join("other"), "a.txt", b"a\n");
10091
    other.commit("a", &[]).unwrap();
10092
    assert!(other.push("origin", false).unwrap()[0].ok);
10093
    let mut one = Repo::clone(&url, &root.join("one"))
10094
        .unwrap()
10095
        .with_home(root.join("home"));
10096
    one.config.set("remote.earth.url", &url).unwrap();
10097
    one.config.set("remote.gcs.url", &url).unwrap();
10098
    one.config.set("remote.origin.url", "").unwrap();
10099
    one.save_config().unwrap();
10100
    write(&root.join("other"), "b.txt", b"b\n");
10101
    other.commit("b", &[]).unwrap();
10102
    assert!(other.push("origin", false).unwrap()[0].ok);
10103
    one.fetch("earth").unwrap();
10104
    let b = one
10105
        .bookmarks()
10106
        .unwrap()
10107
        .into_iter()
10108
        .find(|b| b.name == "main")
10109
        .unwrap();
10110
    assert_eq!(
10111
        (b.remote.as_deref(), b.behind),
10112
        (Some("earth"), Some(1)),
10113
        "a stale origin copy is not used"
10114
    );
10115
    assert_eq!(
10116
        one.default_remote(),
10117
        "origin",
10118
        "no default chosen among several"
10119
    );
10120
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
10121
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
10122
    one.config.set("core.remote", "earth").unwrap();
10123
    assert_eq!(one.default_remote(), "earth");
10124
}
10125
10126
#[test]
10127
fn a_missing_author_identity_says_how_to_fix_it() {
10128
    // oxygen#82: an agent home's author.key naming an identity the
10129
    // repository does not hold.
10130
    hermetic();
10131
    let dir = tempfile::tempdir().unwrap();
10132
    let mut repo = Repo::init(dir.path()).unwrap();
10133
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
10134
    repo.config.set("author.key", &missing.to_hex()).unwrap();
10135
    let e = repo.identity(&missing).unwrap_err().to_string();
10136
    assert!(
10137
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
10138
        "{e}"
10139
    );
10140
    assert!(e.contains("this repository's config"), "{e}");
10141
}
10142
10143
#[test]
10144
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
10145
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
10146
    // the working copy, a pull with nothing new left it there, and status
10147
    // said "clean".
10148
    hermetic();
10149
    let dir = tempfile::tempdir().unwrap();
10150
    let root = dir.path();
10151
    let _up = Repo::init(&root.join("up")).unwrap();
10152
    let url = root.join("up").to_string_lossy().to_string();
10153
    let other = Repo::clone(&url, &root.join("other"))
10154
        .unwrap()
10155
        .with_home(root.join("home"));
10156
    write(&root.join("other"), "a.txt", b"a\n");
10157
    other.commit("a", &[]).unwrap();
10158
    assert!(other.push("origin", false).unwrap()[0].ok);
10159
    let one = Repo::clone(&url, &root.join("one"))
10160
        .unwrap()
10161
        .with_home(root.join("home"));
10162
    write(&root.join("other"), "b.txt", b"b\n");
10163
    other.commit("b", &[]).unwrap();
10164
    assert!(other.push("origin", false).unwrap()[0].ok);
10165
    one.fetch("origin").unwrap();
10166
    // The bookmark moves; the working copy does not.
10167
    let theirs = one.resolve_heads("origin/main").unwrap();
10168
    one.bookmark_set("main", &theirs).unwrap();
10169
    assert!(!root.join("one/b.txt").exists());
10170
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
10171
    let r = one.pull("origin").unwrap();
10172
    assert!(
10173
        !r.changed && r.checked_out,
10174
        "nothing new, but the working copy caught up"
10175
    );
10176
    assert!(root.join("one/b.txt").exists());
10177
    assert_eq!(one.working_copy_behind().unwrap(), None);
10178
}
10179
10180
#[test]
10181
fn touched_nodes_cache_answers_as_the_changes_do() {
10182
    hermetic();
10183
    let dir = tempfile::tempdir().unwrap();
10184
    let repo = Repo::init(dir.path()).unwrap();
10185
    write(dir.path(), "a.txt", b"one\n");
10186
    write(dir.path(), "b.txt", b"x\n");
10187
    repo.snapshot("t").unwrap();
10188
    let c1 = repo.commit("first", &[]).unwrap();
10189
    write(dir.path(), "b.txt", b"y\n");
10190
    repo.snapshot("t").unwrap();
10191
    repo.commit("b only", &[]).unwrap();
10192
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
10193
    write(dir.path(), "c.txt", b"one\ntwo\n");
10194
    repo.snapshot("t").unwrap();
10195
    let c3 = repo.commit("rename and edit", &[]).unwrap();
10196
    // Uncommitted work, so the working copy touches a file too.
10197
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
10198
    repo.snapshot("t").unwrap();
10199
10200
    let path = dir.path().join(".oxy/index/touched");
10201
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
10202
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
10203
    assert!(path.exists(), "the first query writes the cache");
10204
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
10205
    assert_eq!(cold, warm, "the cache answers as the changes do");
10206
    let (wc, _) = repo.working_copy().unwrap();
10207
    assert_eq!(
10208
        cold,
10209
        vec![wc, c3, c1],
10210
        "renames followed, the working copy included"
10211
    );
10212
10213
    // Working-copy changes are not kept: they are replaced by every snapshot.
10214
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
10215
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
10216
    assert!(cached.contains(&c1) && cached.contains(&c3));
10217
10218
    // A damaged cache is ignored, not trusted.
10219
    let mut bytes = fs::read(&path).unwrap();
10220
    let last = bytes.len() - 40;
10221
    bytes[last] ^= 1;
10222
    fs::write(&path, &bytes).unwrap();
10223
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
10224
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
10225
    assert_eq!(hashes(touches), vec![c3, c1]);
10226
}
10227
10228
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
10229
/// file back where it was leave two placements at one place, which the
10230
/// tree shows as one file. Removing it, and then its directory, retires
10231
/// both, so no copy is left under a directory that is gone.
10232
#[test]
10233
fn git_import_removes_every_copy_of_a_file_at_one_place() {
10234
    hermetic();
10235
    if std::process::Command::new("git")
10236
        .arg("--version")
10237
        .output()
10238
        .is_err()
10239
    {
10240
        eprintln!("git not installed; skipping");
10241
        return;
10242
    }
10243
    let dir = tempfile::tempdir().unwrap();
10244
    let root = dir.path();
10245
    let g = root.join("src.git");
10246
    fs::create_dir_all(&g).unwrap();
10247
    let git = |args: &[&str]| {
10248
        let out = std::process::Command::new("git")
10249
            .arg("-C")
10250
            .arg(&g)
10251
            .args([
10252
                "-c",
10253
                "user.name=Grace",
10254
                "-c",
10255
                "[email protected]",
10256
                "-c",
10257
                "commit.gpgsign=false",
10258
            ])
10259
            .args(args)
10260
            .output()
10261
            .unwrap();
10262
        assert!(
10263
            out.status.success(),
10264
            "git {args:?}: {}",
10265
            String::from_utf8_lossy(&out.stderr)
10266
        );
10267
    };
10268
    git(&["init", "-q", "-b", "main"]);
10269
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
10270
    write(&g, "keep.txt", b"k\n");
10271
    git(&["add", "."]);
10272
    git(&["commit", "-qm", "base"]);
10273
    fs::create_dir_all(g.join("d/sub")).unwrap();
10274
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
10275
    git(&["commit", "-qm", "into sub"]);
10276
    git(&["checkout", "-qb", "side"]);
10277
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
10278
    git(&["commit", "-qm", "back, on side"]);
10279
    git(&["checkout", "-q", "main"]);
10280
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
10281
    git(&["commit", "-qm", "back, on main"]);
10282
    git(&["merge", "-q", "--no-edit", "side"]);
10283
    git(&["rm", "-rq", "d"]);
10284
    git(&["commit", "-qm", "d goes"]);
10285
10286
    let repo = Repo::init(&root.join("o")).unwrap();
10287
    repo.import_git(&g, "main").unwrap();
10288
    let v = repo.verify_git_import(&g, "main").unwrap();
10289
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
10290
    let st = repo
10291
        .load_state_history(&repo.bookmark_heads().unwrap())
10292
        .unwrap();
10293
    let view = st.tree().view();
10294
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
10295
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
10296
}
10297
10298
/// oxygen#94: a state index's file histories are read, and checked by
10299
/// their own hashes, only when a file is built. One found damaged is an
10300
/// error that says so, the index is removed, and the next read rebuilds it.
10301
#[test]
10302
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
10303
    hermetic();
10304
    let dir = tempfile::tempdir().unwrap();
10305
    let repo = Repo::init(dir.path()).unwrap();
10306
    for i in 0..6 {
10307
        write(
10308
            dir.path(),
10309
            &format!("f{i}.txt"),
10310
            format!("one {i}\n").as_bytes(),
10311
        );
10312
    }
10313
    repo.snapshot("t").unwrap();
10314
    repo.commit("first", &[]).unwrap();
10315
    for i in 0..6 {
10316
        write(
10317
            dir.path(),
10318
            &format!("f{i}.txt"),
10319
            format!("one {i}\ntwo\n").as_bytes(),
10320
        );
10321
    }
10322
    repo.snapshot("t").unwrap();
10323
    repo.commit("second", &[]).unwrap();
10324
    let want: Vec<Vec<u8>> = (0..6)
10325
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
10326
        .collect();
10327
    // The index of the working copy's base, holding every file's history
10328
    // (a few changes behind, an index is replayed onto, not rewritten).
10329
    let (_, wc) = repo.working_copy().unwrap();
10330
    let base = repo.load_state_history(&wc.deps).unwrap();
10331
    repo.write_state_index(&wc.deps, &base);
10332
    for (i, w) in want.iter().enumerate() {
10333
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
10334
    }
10335
    let index = repo.state_indexes();
10336
    assert!(!index.is_empty(), "a state index was written");
10337
    // The histories are last in the file: damage the last of them.
10338
    let mut bytes = fs::read(&index[0]).unwrap();
10339
    let last = bytes.len() - 1;
10340
    bytes[last] ^= 0x40;
10341
    fs::write(&index[0], &bytes).unwrap();
10342
10343
    let reads: Vec<_> = (0..6)
10344
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
10345
        .collect();
10346
    let damaged: Vec<String> = reads
10347
        .iter()
10348
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
10349
        .collect();
10350
    assert_eq!(damaged.len(), 1, "{damaged:?}");
10351
    assert!(
10352
        damaged[0].contains("state index was damaged")
10353
            && damaged[0].contains("run the command again"),
10354
        "{}",
10355
        damaged[0]
10356
    );
10357
    // Every file reads right again, from an index rebuilt from history.
10358
    for (i, w) in want.iter().enumerate() {
10359
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
10360
    }
10361
}
10362
10363
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
10364
/// objects alone and in dependency order, and the last moves the bookmark.
10365
/// The remote ends with every change and the same state, and says how each
10366
/// part went.
10367
#[test]
10368
fn a_long_push_goes_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
    // One byte: every change is a part of its own.
10380
    repo.config.set("push.batch-bytes", "1").unwrap();
10381
    repo.save_config().unwrap();
10382
    for i in 0..6 {
10383
        write(
10384
            &main,
10385
            &format!("f{i}.txt"),
10386
            format!("file {i}\n").as_bytes(),
10387
        );
10388
        repo.commit(&format!("c{i}"), &[]).unwrap();
10389
    }
10390
    let mut parts = Vec::new();
10391
    let results = repo
10392
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
10393
        .unwrap();
10394
    assert!(
10395
        results.iter().any(|r| r.ok && r.name == "main"),
10396
        "{results:?}"
10397
    );
10398
    assert_eq!(parts.len(), 6, "{parts:?}");
10399
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
10400
10401
    let remote = Repo::open(&origin).unwrap();
10402
    let heads = repo.bookmark_heads().unwrap();
10403
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
10404
    assert_eq!(
10405
        remote.log_state(&heads).unwrap().len(),
10406
        repo.log_state(&heads).unwrap().len()
10407
    );
10408
    // A push of objects alone reports how it went, as `objects`.
10409
    let got = remote
10410
        .receive_push(Bundle::default(), vec![], None, vec![])
10411
        .unwrap();
10412
    assert_eq!(got.len(), 1);
10413
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
10414
}
10415
10416
/// oxygen#133: one change whose blobs pass `push.batch-bytes` sends them
10417
/// first, in parts of objects alone, so no request is larger than about
10418
/// that (a proxy in front of a hub refuses one past 100 MB); the change
10419
/// and the bookmark follow, and a clone has every file.
10420
#[test]
10421
fn a_heavy_change_sends_its_blobs_in_parts() {
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.config.set("push.batch-bytes", "50000").unwrap();
10433
    repo.save_config().unwrap();
10434
    let mut x: u64 = 0x9e3779b97f4a7c15;
10435
    let mut noise = |n: usize| -> Vec<u8> {
10436
        (0..n)
10437
            .map(|_| {
10438
                x ^= x << 13;
10439
                x ^= x >> 7;
10440
                x ^= x << 17;
10441
                (x >> 24) as u8
10442
            })
10443
            .collect()
10444
    };
10445
    let files: Vec<Vec<u8>> = (0..4).map(|_| noise(40_000)).collect();
10446
    for (i, f) in files.iter().enumerate() {
10447
        write(&main, &format!("bin{i}.dat"), f);
10448
    }
10449
    repo.commit("four blobs", &[]).unwrap();
10450
    let mut parts = Vec::new();
10451
    let results = repo
10452
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
10453
        .unwrap();
10454
    assert!(
10455
        results.iter().any(|r| r.ok && r.name == "main"),
10456
        "{results:?}"
10457
    );
10458
    assert!(
10459
        parts.len() >= 3 && parts[0].starts_with("objects 1 of"),
10460
        "{parts:?}"
10461
    );
10462
    let back = Repo::clone(&origin.to_string_lossy(), &root.join("back")).unwrap();
10463
    for (i, f) in files.iter().enumerate() {
10464
        assert_eq!(&fs::read(root.join(format!("back/bin{i}.dat"))).unwrap(), f);
10465
    }
10466
    drop(back);
10467
}
10468
10469
/// oxygen#136: a bundle carries a replaced binary file's new content
10470
/// only. Its old content came with the change that added it, so removing
10471
/// or replacing a file sends no old blob again; the remote and a clone of
10472
/// it are whole.
10473
#[test]
10474
fn a_replacement_does_not_send_the_old_content_again() {
10475
    hermetic();
10476
    let dir = tempfile::tempdir().unwrap();
10477
    let root = dir.path();
10478
    let origin = root.join("origin");
10479
    Repo::init_bare_unbound(&origin).unwrap();
10480
    let main = root.join("main");
10481
    let mut repo = Repo::init(&main).unwrap();
10482
    repo.config
10483
        .set("remote.origin.url", &origin.to_string_lossy())
10484
        .unwrap();
10485
    repo.save_config().unwrap();
10486
    let blobs = |b: &Bundle| {
10487
        b.objects
10488
            .iter()
10489
            .filter(|(ty, _)| *ty == ObjectType::Blob)
10490
            .count()
10491
    };
10492
    write(&main, "bin.dat", b"\0\x01first binary");
10493
    write(&main, "gone.dat", b"\0\x02to be removed");
10494
    let added = repo.commit("add", &[]).unwrap();
10495
    assert!(repo.push("origin", false).unwrap()[0].ok);
10496
    write(&main, "bin.dat", b"\0\x01second binary");
10497
    fs::remove_file(main.join("gone.dat")).unwrap();
10498
    let changed = repo.commit("replace and remove", &[]).unwrap();
10499
    assert_eq!(blobs(&repo.bundle_for(&[changed]).unwrap()), 1);
10500
    assert_eq!(blobs(&repo.bundle_for(&[added, changed]).unwrap()), 3);
10501
    assert!(repo.push("origin", false).unwrap()[0].ok);
10502
    let origin = Repo::open(&origin).unwrap();
10503
    assert_eq!(origin.fsck().unwrap().problems, vec![]);
10504
    let back = Repo::clone(&origin.root().to_string_lossy(), &root.join("back")).unwrap();
10505
    assert_eq!(back.fsck().unwrap().problems, vec![]);
10506
    assert_eq!(
10507
        fs::read(root.join("back/bin.dat")).unwrap(),
10508
        b"\0\x01second binary"
10509
    );
10510
    assert!(!root.join("back/gone.dat").exists());
10511
}
10512
10513
/// oxygen#97: with `git.claim`, an import authors the importing identity's
10514
/// own commits (Git author email = its email, any case) with its key, and
10515
/// leaves anyone else's with the zero key; the history verifies as before.
10516
#[test]
10517
fn git_import_claims_your_own_commits() {
10518
    hermetic();
10519
    if std::process::Command::new("git")
10520
        .arg("--version")
10521
        .output()
10522
        .is_err()
10523
    {
10524
        eprintln!("git not installed; skipping");
10525
        return;
10526
    }
10527
    let dir = tempfile::tempdir().unwrap();
10528
    let root = dir.path();
10529
    let g = root.join("src.git");
10530
    fs::create_dir_all(&g).unwrap();
10531
    let git = |who: &str, args: &[&str]| {
10532
        let (name, email) = who.split_once(' ').unwrap();
10533
        let out = std::process::Command::new("git")
10534
            .arg("-C")
10535
            .arg(&g)
10536
            .args([
10537
                "-c",
10538
                &format!("user.name={name}"),
10539
                "-c",
10540
                &format!("user.email={email}"),
10541
                "-c",
10542
                "commit.gpgsign=false",
10543
            ])
10544
            .args(args)
10545
            .output()
10546
            .unwrap();
10547
        assert!(
10548
            out.status.success(),
10549
            "git {args:?}: {}",
10550
            String::from_utf8_lossy(&out.stderr)
10551
        );
10552
    };
10553
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
10554
    write(&g, "a.txt", b"a\n");
10555
    git("Grace [email protected]", &["add", "."]);
10556
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
10557
    write(&g, "b.txt", b"b\n");
10558
    git("Ada [email protected]", &["add", "."]);
10559
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
10560
10561
    let mut repo = Repo::init(&root.join("o")).unwrap();
10562
    let (key, _) = repo
10563
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
10564
        .unwrap();
10565
    repo.config.set("git.claim", "true").unwrap();
10566
    repo.save_config().unwrap();
10567
    let repo = Repo::open(&root.join("o")).unwrap();
10568
    repo.import_git(&g, "main").unwrap();
10569
    let v = repo.verify_git_import(&g, "main").unwrap();
10570
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
10571
    let heads = repo.bookmark_heads().unwrap();
10572
    let by_message: std::collections::HashMap<String, KeyId> = repo
10573
        .log_state(&heads)
10574
        .unwrap()
10575
        .into_iter()
10576
        .map(|e| {
10577
            (
10578
                e.change.message.lines().next().unwrap_or("").to_string(),
10579
                e.change.author,
10580
            )
10581
        })
10582
        .collect();
10583
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
10584
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
10585
}
10586
10587
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
10588
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
10589
#[test]
10590
fn removing_a_remote_leaves_nothing_of_it() {
10591
    hermetic();
10592
    let dir = tempfile::tempdir().unwrap();
10593
    let origin = dir.path().join("origin");
10594
    Repo::init_bare_unbound(&origin).unwrap();
10595
    let main = dir.path().join("main");
10596
    let mut repo = Repo::init(&main).unwrap();
10597
    repo.config
10598
        .set("remote.origin.url", &origin.to_string_lossy())
10599
        .unwrap();
10600
    repo.config
10601
        .set("remote.origin.token", "secret-ish")
10602
        .unwrap();
10603
    repo.config
10604
        .set("remote.keep.url", &origin.to_string_lossy())
10605
        .unwrap();
10606
    repo.save_config().unwrap();
10607
    write(&main, "a.txt", b"a\n");
10608
    repo.commit("a", &[]).unwrap();
10609
    assert!(repo.push("origin", false).unwrap()[0].ok);
10610
    assert!(
10611
        repo.view().unwrap().remotes.contains_key("origin"),
10612
        "a tracking bookmark"
10613
    );
10614
10615
    repo.remove_remote("origin").unwrap();
10616
    let again = Repo::open(&main).unwrap();
10617
    assert!(
10618
        !again
10619
            .config
10620
            .repo_layer()
10621
            .keys()
10622
            .any(|k| k.starts_with("remote.origin.")),
10623
        "{:?}",
10624
        again.config.repo_layer()
10625
    );
10626
    assert!(!again.config.remotes.contains_key("origin"));
10627
    assert!(
10628
        !again.view().unwrap().remotes.contains_key("origin"),
10629
        "its tracking bookmarks go"
10630
    );
10631
    assert!(
10632
        again.config.remotes.contains_key("keep"),
10633
        "another remote stays"
10634
    );
10635
    let mut again = again;
10636
    assert!(
10637
        again.remove_remote("origin").is_err(),
10638
        "a second removal is refused"
10639
    );
10640
}
10641
10642
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
10643
/// unreachable from history, so gc prunes it, unless the host names it:
10644
/// then it and its chunks stay, and it reads back whole.
10645
#[test]
10646
fn gc_keeps_the_blobs_a_host_names() {
10647
    hermetic();
10648
    let dir = tempfile::tempdir().unwrap();
10649
    let repo = Repo::init(dir.path()).unwrap();
10650
    write(dir.path(), "a.txt", b"a\n");
10651
    repo.commit("a", &[]).unwrap();
10652
    // Large enough to be several chunks.
10653
    let body: Vec<u8> = (0..400_000u32)
10654
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
10655
        .collect();
10656
    let kept = repo.store_blob(&body).unwrap();
10657
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
10658
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
10659
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
10660
    assert!(!repo.store().has(&lost), "not named: pruned");
10661
    repo.gc(true).unwrap();
10662
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
10663
}
10664
10665
/// oxygen#99: undo in one workspace undoes that workspace's last command,
10666
/// never another workspace's, says what it undid, and goes further back
10667
/// when run again.
10668
#[test]
10669
fn undo_is_scoped_to_its_workspace() {
10670
    hermetic();
10671
    let dir = tempfile::tempdir().unwrap();
10672
    let root = dir.path().join("main");
10673
    let a = Repo::init(&root).unwrap();
10674
    write(&root, "base.txt", b"base\n");
10675
    let base = a.commit("base", &[]).unwrap();
10676
    a.bookmark_create("feature", None).unwrap();
10677
    let ws_dir = dir.path().join("ws");
10678
    let heads = a.resolve_heads("feature").unwrap();
10679
    let b = a
10680
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
10681
        .unwrap();
10682
10683
    // A commits on main, then B commits on feature: B's is the newest.
10684
    write(&root, "a.txt", b"a\n");
10685
    let ca = a.commit("from a", &[]).unwrap();
10686
    write(&ws_dir, "b.txt", b"b\n");
10687
    let cb = b.commit("from b", &[]).unwrap();
10688
10689
    // A's undo undoes A's commit and leaves B's.
10690
    let u = a.undo().unwrap();
10691
    assert_eq!(u.command, "oxy commit -m \"from a\"");
10692
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
10693
    assert!(!u.changes.is_empty());
10694
    let view = a.view().unwrap();
10695
    // (Independent changes commute, so a bookmark's heads may hold base too.)
10696
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
10697
    assert!(
10698
        a.heads_of(&view, "feature").unwrap().contains(&cb),
10699
        "B's commit stands"
10700
    );
10701
    assert!(
10702
        a.store().get_change(&ca).is_ok(),
10703
        "the change itself is still in the store"
10704
    );
10705
    // A's working copy was clean, so its files followed; B's are untouched.
10706
    assert!(!root.join("a.txt").exists());
10707
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
10708
    assert!(ws_dir.join("b.txt").exists());
10709
10710
    // B's undo still finds B's own commit, under A's undo.
10711
    let u = b.undo().unwrap();
10712
    assert_eq!(u.command, "oxy commit -m \"from b\"");
10713
    assert!(!b
10714
        .heads_of(&b.view().unwrap(), "feature")
10715
        .unwrap()
10716
        .contains(&cb));
10717
    assert_eq!(
10718
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
10719
        vec![base],
10720
        "A's undo stands"
10721
    );
10722
10723
    // A's next undo goes past the commit it already undid, to adding B's
10724
    // workspace: refused, since B has worked there since.
10725
    let e = a.undo().unwrap_err().to_string();
10726
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
10727
}
10728
10729
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
10730
/// own commit's head, and the other workspace's head stays.
10731
#[test]
10732
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
10733
    hermetic();
10734
    let dir = tempfile::tempdir().unwrap();
10735
    let root = dir.path().join("main");
10736
    let a = Repo::init(&root).unwrap();
10737
    write(&root, "base.txt", b"base\n");
10738
    a.commit("base", &[]).unwrap();
10739
    let ws_dir = dir.path().join("ws");
10740
    let b = a.workspace_add(&ws_dir, None).unwrap();
10741
    write(&root, "a.txt", b"a\n");
10742
    let ca = a.commit("from a", &[]).unwrap();
10743
    write(&ws_dir, "b.txt", b"b\n");
10744
    let cb = b.commit("from b", &[]).unwrap();
10745
    let u = a.undo().unwrap();
10746
    assert_eq!(u.command, "oxy commit -m \"from a\"");
10747
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
10748
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
10749
}
10750
10751
/// oxygen#99: an undo that would also take back what another workspace
10752
/// did since to the same bookmark is refused, naming it.
10753
#[test]
10754
fn undo_refuses_to_take_back_another_workspaces_work() {
10755
    hermetic();
10756
    let dir = tempfile::tempdir().unwrap();
10757
    let root = dir.path().join("main");
10758
    let a = Repo::init(&root).unwrap();
10759
    write(&root, "base.txt", b"base\n");
10760
    a.commit("base", &[]).unwrap();
10761
    let ws_dir = dir.path().join("ws");
10762
    let b = a.workspace_add(&ws_dir, None).unwrap();
10763
    // Both on main: A commits, then B builds on it, editing A's file.
10764
    write(&root, "a.txt", b"a\n");
10765
    a.commit("from a", &[]).unwrap();
10766
    b.refresh().unwrap();
10767
    let heads = b.resolve_heads("main").unwrap();
10768
    b.checkout(&heads, false, "oxy checkout").unwrap();
10769
    write(&ws_dir, "a.txt", b"a, then b\n");
10770
    b.commit("from b", &[]).unwrap();
10771
    let e = a.undo().unwrap_err().to_string();
10772
    assert!(
10773
        e.contains("bookmark main") && e.contains("builds on"),
10774
        "{e}"
10775
    );
10776
    assert!(e.contains("oxy op restore"), "{e}");
10777
}
10778
10779
/// oxygen#99: undoing a commit that was already pushed says so: the remote
10780
/// still has it.
10781
#[test]
10782
fn undo_says_when_the_commit_was_pushed() {
10783
    hermetic();
10784
    let dir = tempfile::tempdir().unwrap();
10785
    let root = dir.path();
10786
    Repo::init(&root.join("origin")).unwrap();
10787
    let url = root.join("origin").to_string_lossy().to_string();
10788
    let repo = Repo::clone(&url, &root.join("work"))
10789
        .unwrap()
10790
        .with_home(root.join("home"));
10791
    write(&root.join("work"), "a.txt", b"a\n");
10792
    repo.commit("a", &[]).unwrap();
10793
    assert!(repo.push("origin", false).unwrap()[0].ok);
10794
    // The push itself is passed over: the remote keeps what it was sent.
10795
    let u = repo.undo().unwrap();
10796
    assert_eq!(u.command, "oxy commit -m \"a\"");
10797
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
10798
}
10799
10800
/// oxygen#98: a new untracked file over snapshot.max-new-file-size is left
10801
/// out of the snapshot and named; tracked files and files already in the
10802
/// working copy are not.
10803
#[test]
10804
fn large_new_files_are_left_out_of_snapshots() {
10805
    hermetic();
10806
    let dir = tempfile::tempdir().unwrap();
10807
    let root = dir.path();
10808
    let mut repo = Repo::init(root).unwrap();
10809
    repo.config.max_new_file = 1024;
10810
    write(root, "small.txt", b"small\n");
10811
    write(root, "big.bin", &vec![0u8; 4096]);
10812
    let s = repo.snapshot("oxy status").unwrap();
10813
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
10814
    assert_eq!(paths, ["small.txt"]);
10815
    assert_eq!(repo.skipped_large(), vec![("big.bin".to_string(), 4096)]);
10816
    repo.commit("small", &[]).unwrap();
10817
10818
    // A tracked file may grow past the limit.
10819
    write(root, "small.txt", &vec![b'x'; 4096]);
10820
    let s = repo.snapshot("oxy status").unwrap();
10821
    assert!(s.statuses.iter().any(|p| p.path == "small.txt"));
10822
    // With no limit the big file is taken in, and stays once it is.
10823
    repo.config.max_new_file = 0;
10824
    let s = repo.snapshot("oxy status").unwrap();
10825
    assert!(s.statuses.iter().any(|p| p.path == "big.bin"));
10826
    repo.config.max_new_file = 1024;
10827
    let s = repo.snapshot("oxy status").unwrap();
10828
    assert!(
10829
        s.statuses.iter().any(|p| p.path == "big.bin"),
10830
        "already in the working copy"
10831
    );
10832
    assert!(repo.skipped_large().is_empty());
10833
}
10834
10835
/// oxygen#98: a file only a past working-copy snapshot held is pruned once
10836
/// snapshots expire, and kept while they have not.
10837
#[test]
10838
fn gc_prunes_what_only_expired_snapshots_held() {
10839
    hermetic();
10840
    let dir = tempfile::tempdir().unwrap();
10841
    let root = dir.path();
10842
    let mut repo = Repo::init(root).unwrap();
10843
    repo.config.gc_grace_days = 0;
10844
    write(root, "a.txt", b"a\n");
10845
    repo.commit("a", &[]).unwrap();
10846
    let image: Vec<u8> = (0..200_000u32).map(|i| (i % 7) as u8).collect();
10847
    write(root, "image.tar", &image);
10848
    repo.snapshot("oxy status").unwrap();
10849
    std::fs::remove_file(root.join("image.tar")).unwrap();
10850
    repo.snapshot("oxy status").unwrap();
10851
    let blob = Repo::blob_ref(&image);
10852
    assert!(repo.store().has(&blob));
10853
    repo.gc(true).unwrap();
10854
    assert!(repo.store().has(&blob), "a recent snapshot keeps it");
10855
    repo.config.snapshot_retention_days = 0;
10856
    repo.gc(true).unwrap();
10857
    assert!(!repo.store().has(&blob), "an expired snapshot does not");
10858
    assert_eq!(
10859
        repo.file_at("a.txt", None).unwrap(),
10860
        b"a\n",
10861
        "committed files stay"
10862
    );
10863
}
10864
10865
/// oxygen#100: uncommitted work byte-for-byte what the bookmark switched to
10866
/// already has is no conflict: the switch goes through, nothing is lost,
10867
/// and other carried work still comes along.
10868
#[test]
10869
fn carrying_work_the_target_already_has_is_no_conflict() {
10870
    hermetic();
10871
    let dir = tempfile::tempdir().unwrap();
10872
    let root = dir.path();
10873
    let mut repo = Repo::init(root).unwrap();
10874
    write(root, "a.txt", b"one\n");
10875
    write(root, "b.txt", b"b\n");
10876
    repo.commit("one", &[]).unwrap();
10877
    repo.bookmark_create("landed", None).unwrap();
10878
    // On landed, a.txt becomes "two" (as a proposal landing would).
10879
    repo.bookmark_switch("landed", false).unwrap();
10880
    write(root, "a.txt", b"two\n");
10881
    repo.commit("two", &[]).unwrap();
10882
    repo.bookmark_switch("main", false).unwrap();
10883
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"one\n");
10884
    // The same edit, uncommitted, on main; and another edit besides.
10885
    write(root, "a.txt", b"two\n");
10886
    write(root, "b.txt", b"b, edited\n");
10887
    let (_, carried) = repo.bookmark_switch_carry("landed").unwrap();
10888
    assert_eq!(
10889
        carried,
10890
        vec!["b.txt".to_string()],
10891
        "only the work landed lacks is carried"
10892
    );
10893
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"two\n");
10894
    assert_eq!(std::fs::read(root.join("b.txt")).unwrap(), b"b, edited\n");
10895
    let s = repo.snapshot("oxy status").unwrap();
10896
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
10897
    assert_eq!(paths, ["b.txt"]);
10898
10899
    // A real difference is still refused.
10900
    repo.bookmark_switch("main", true).unwrap();
10901
    write(root, "a.txt", b"three\n");
10902
    let e = repo
10903
        .bookmark_switch_carry("landed")
10904
        .unwrap_err()
10905
        .to_string();
10906
    assert!(e.contains("a.txt") && e.contains("--discard"), "{e}");
10907
}
10908
10909
/// oxygen#103: a full change hash as `--json` prints it, without `#`,
10910
/// resolves, so JSON output feeds back into commands.
10911
#[test]
10912
fn a_full_hash_resolves_without_its_hash_sign() {
10913
    hermetic();
10914
    let dir = tempfile::tempdir().unwrap();
10915
    let root = dir.path();
10916
    let repo = Repo::init(root).unwrap();
10917
    write(root, "a.txt", b"a\n");
10918
    let h = repo.commit("a", &[]).unwrap();
10919
    assert_eq!(repo.resolve_change(&h.to_hex()).unwrap(), h);
10920
    assert_eq!(repo.resolve_change(&format!("#{}", h.to_hex())).unwrap(), h);
10921
    assert!(repo
10922
        .resolve_change(&"0".repeat(64))
10923
        .unwrap_err()
10924
        .to_string()
10925
        .contains("no change matches"));
10926
}
10927
10928
#[test]
10929
fn a_pin_change_moves_only_the_pin() {
10930
    hermetic();
10931
    let dir = tempfile::tempdir().unwrap();
10932
    let root = dir.path();
10933
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
10934
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
10935
    let lib = Repo::clone(&lib_url, &root.join("lib"))
10936
        .unwrap()
10937
        .with_home(root.join("home"));
10938
    write(&root.join("lib"), "lib.txt", b"v1\n");
10939
    lib.commit("lib v1", &[]).unwrap();
10940
    assert!(lib.push("origin", false).unwrap()[0].ok);
10941
    let _app_origin = Repo::init(&root.join("app-origin")).unwrap();
10942
    let app_dir = root.join("app");
10943
    let app = Repo::clone(&root.join("app-origin").to_string_lossy(), &app_dir)
10944
        .unwrap()
10945
        .with_home(root.join("home"));
10946
    write(&app_dir, "main.txt", b"app\n");
10947
    let pin1 = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
10948
    let a1 = app.commit("app with lib", &[]).unwrap();
10949
    // The library moves on.
10950
    write(&root.join("lib"), "more.txt", b"v2\n");
10951
    let l2 = lib.commit("lib v2", &[]).unwrap();
10952
    let crate::subrepo::Pin::Oxy { repo, bookmark, .. } = pin1 else {
10953
        panic!("an Oxygen pin")
10954
    };
10955
    let pin2 = crate::subrepo::Pin::Oxy {
10956
        repo,
10957
        heads: vec![l2],
10958
        bookmark,
10959
    };
10960
    let author = app.store().get_change(&a1).unwrap().author;
10961
    let change = app
10962
        .build_pin_change(&[a1], "libs/lib", &pin2, "Move lib to v2", author)
10963
        .unwrap();
10964
    let mut state = app.load_state(&[a1]).unwrap();
10965
    state.add(change).unwrap();
10966
    let files = state.materialize().files;
10967
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
10968
    let FileContent::Opaque { blobs } = &files["libs/lib"].content else {
10969
        panic!("a pin is opaque")
10970
    };
10971
    let read = crate::subrepo::Pin::decode(&app.read_blob(&blobs[0]).unwrap()).unwrap();
10972
    assert_eq!(read, pin2, "the new pin");
10973
    assert!(
10974
        matches!(&files["main.txt"].content, FileContent::Text { bytes, .. } if bytes.as_slice() == b"app\n"),
10975
        "nothing else changes"
10976
    );
10977
    // Only a subrepo's pin can be moved this way.
10978
    let e = app.build_pin_change(&[a1], "main.txt", &pin2, "x", author);
10979
    assert!(format!("{:?}", e.unwrap_err()).contains("not a subrepo"));
10980
    let e = app.build_pin_change(&[a1], "libs/none", &pin2, "x", author);
10981
    assert!(format!("{:?}", e.unwrap_err()).contains("does not exist"));
10982
}
10983
10984
/// oxygenhub#249: a handle reads the operation head once and keeps it,
10985
/// so one command or request never mixes two heads; another handle's
10986
/// operation shows only after `refresh`. Its own operations move it, and
10987
/// one recorded from the head it kept merges with what landed since, as
10988
/// any concurrent operation does.
10989
#[test]
10990
fn one_handle_keeps_one_head_until_it_refreshes() {
10991
    hermetic();
10992
    let dir = tempfile::tempdir().unwrap();
10993
    let root = dir.path();
10994
    let writer = Repo::init(root).unwrap();
10995
    write(root, "a.txt", b"one\n");
10996
    let h1 = writer.commit("one", &[]).unwrap();
10997
    let reader = Repo::open(root).unwrap();
10998
    let before = reader.view().unwrap();
10999
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
11000
    write(root, "a.txt", b"two\n");
11001
    let h2 = writer.commit("two", &[]).unwrap();
11002
    assert_eq!(
11003
        writer.bookmark_heads().unwrap(),
11004
        vec![h2],
11005
        "its own operation"
11006
    );
11007
    assert_eq!(reader.view().unwrap(), before, "the head it read first");
11008
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
11009
    reader.refresh().unwrap();
11010
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h2]);
11011
11012
    // A handle recording from an older head merges with the newer one.
11013
    let stale = Repo::open(root).unwrap();
11014
    assert_eq!(stale.bookmark_heads().unwrap(), vec![h2]);
11015
    write(root, "a.txt", b"three\n");
11016
    let h3 = writer.commit("three", &[]).unwrap();
11017
    stale.bookmark_create("feature", Some(&[h1])).unwrap();
11018
    let view = stale.view().unwrap();
11019
    assert!(view.bookmarks.contains_key("feature"));
11020
    assert_eq!(
11021
        stale.bookmark_heads().unwrap(),
11022
        vec![h3],
11023
        "merged, not lost"
11024
    );
11025
    let fresh = Repo::open(root).unwrap();
11026
    assert_eq!(fresh.view().unwrap(), view);
11027
}
11028
11029
/// oxygenhub#249 over a store (a bucket's compare-and-swap): the same.
11030
#[test]
11031
fn over_a_store_one_handle_keeps_one_head() {
11032
    hermetic();
11033
    let backend = std::sync::Arc::new(crate::strata::MemoryStore::new());
11034
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
11035
    let dir = tempfile::tempdir().unwrap();
11036
    let a = Repo::init(dir.path()).unwrap();
11037
    let (h0, _) = a.head_op().unwrap();
11038
    let b = Repo::open(dir.path()).unwrap();
11039
    assert_eq!(b.head_op().unwrap().0, h0);
11040
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
11041
    let mut view = a.view().unwrap();
11042
    view.bookmarks.insert("x".into(), state);
11043
    let r = a.record_op(&[h0], "bookmark x", view).unwrap();
11044
    assert_eq!(a.head_op().unwrap().0, r);
11045
    assert_eq!(b.head_op().unwrap().0, h0, "b keeps its head");
11046
    b.refresh().unwrap();
11047
    assert_eq!(b.head_op().unwrap().0, r);
11048
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
11049
}
11050
11051
/// oxygenhub#249: gc retires what it repacks rather than deleting it; a
11052
/// reader opened before reads on, then and after the next gc deletes the
11053
/// retired files once their hour is up. Younger ones are kept.
11054
#[test]
11055
fn gc_retires_and_a_later_gc_deletes_after_the_hour() {
11056
    hermetic();
11057
    let dir = tempfile::tempdir().unwrap();
11058
    let root = dir.path();
11059
    let repo = Repo::init(root).unwrap();
11060
    let mut heads = Vec::new();
11061
    for i in 0..4 {
11062
        write(root, &format!("f{i}.txt"), format!("{i}\n").as_bytes());
11063
        heads.push(repo.commit(&format!("c{i}"), &[]).unwrap());
11064
    }
11065
    let reader = Repo::open(root).unwrap();
11066
    assert_eq!(reader.log().unwrap().len(), 5);
11067
    let r = repo.gc(true).unwrap();
11068
    assert_eq!(r.retired, crate::store::RetiredReport::default());
11069
    assert_eq!(repo.store().loose_count().unwrap(), 0);
11070
    assert_eq!(reader.log().unwrap().len(), 5, "read on from what it had");
11071
    // Nothing is an hour old yet: a gc keeps it all.
11072
    let r = repo.gc(true).unwrap();
11073
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
11074
    assert!(r.retired.kept > 0, "{r:?}");
11075
    write(root, "f9.txt", b"9\n");
11076
    heads.push(repo.commit("c9", &[]).unwrap());
11077
    crate::store::reader_tests::age_retired(
11078
        repo.store(),
11079
        crate::store::RETIRED_FOR + std::time::Duration::from_secs(60),
11080
    );
11081
    let r = repo.gc(true).unwrap();
11082
    assert!(r.retired.packs >= 1 && r.retired.loose > 0, "{r:?}");
11083
    assert_eq!(r.retired.kept, 0, "{r:?}");
11084
    let r = repo.gc(true).unwrap();
11085
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
11086
    assert!(r.retired.kept > 0, "what the last gc retired is young");
11087
    // The reader opened before all of it still reads everything, from
11088
    // the packs it finds when what it loaded is gone.
11089
    assert_eq!(reader.log().unwrap().len(), 5);
11090
    for h in &heads[..4] {
11091
        reader.store().get_change(h).unwrap();
11092
    }
11093
    reader.refresh().unwrap();
11094
    assert_eq!(reader.log().unwrap().len(), 6);
11095
    let fresh = Repo::open(root).unwrap();
11096
    assert_eq!(
11097
        fresh.store().pack_count(),
11098
        1,
11099
        "retired packs are not loaded"
11100
    );
11101
}
11102
11103
/// oxygenhub#249: a repository opens when its store's pack listing names
11104
/// an index that is not there (deleted between the listing and the read).
11105
#[test]
11106
fn a_repository_opens_when_a_listed_index_is_gone() {
11107
    hermetic();
11108
    let backend = crate::store::reader_tests::racing(true);
11109
    let dyn_backend: std::sync::Arc<crate::store::Backend> = backend.clone();
11110
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(dyn_backend));
11111
    let dir = tempfile::tempdir().unwrap();
11112
    let repo = Repo::init(dir.path()).unwrap();
11113
    write(dir.path(), "a.txt", b"a\n");
11114
    let h = repo.commit("a", &[]).unwrap();
11115
    repo.gc(true).unwrap();
11116
    let again = Repo::open(dir.path()).unwrap();
11117
    assert_eq!(again.store().pack_count(), 1);
11118
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
11119
    // And when one is deleted between the listing and the read: a copy of
11120
    // the live pack, whose index goes as the store opens.
11121
    use crate::strata::Store as _;
11122
    let idx = backend
11123
        .list("pack-")
11124
        .unwrap()
11125
        .into_iter()
11126
        .map(|e| e.key)
11127
        .find(|k| k.ends_with(".idx") && k != "pack-0000.idx")
11128
        .unwrap();
11129
    let stem = idx.trim_end_matches(".idx");
11130
    for ext in ["pack", "idx"] {
11131
        let bytes = backend.get(&format!("{stem}.{ext}")).unwrap();
11132
        backend
11133
            .put_new(&format!("pack-copy.{ext}"), &bytes)
11134
            .unwrap();
11135
    }
11136
    *backend.doomed.lock().unwrap() = Some("pack-copy.idx".into());
11137
    let again = Repo::open(dir.path()).unwrap();
11138
    assert_eq!(again.store().pack_count(), 1);
11139
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
11140
    assert!(!backend.has("pack-copy.idx").unwrap());
11141
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
11142
}
11143
11144
/// oxygen#82: a home with `author.for` authors as the identity its hub
11145
/// last named (kept in `keys/author.for`), not its stale `author.key`; a
11146
/// repository's own `author.key` pin still wins, and without `author.for`
11147
/// the note is ignored.
11148
#[test]
11149
fn author_for_follows_the_key_the_hub_named() {
11150
    let dir = tempfile::tempdir().unwrap();
11151
    let home = dir.path().join("home");
11152
    fs::create_dir_all(home.join("keys")).unwrap();
11153
    let user = home.join("config.toml");
11154
    let repo_cfg = dir.path().join("config");
11155
    let (old, new, pin) = (
11156
        KeyId::from_hex(&"a".repeat(64)).unwrap(),
11157
        KeyId::from_hex(&"b".repeat(64)).unwrap(),
11158
        KeyId::from_hex(&"c".repeat(64)).unwrap(),
11159
    );
11160
    fs::write(&user, format!("author.key = \"{}\"\n", old.to_hex())).unwrap();
11161
    fs::write(
11162
        home.join("keys").join(super::config::AUTHOR_FOR_FILE),
11163
        format!("{}\n", new.to_hex()),
11164
    )
11165
    .unwrap();
11166
    fs::write(&repo_cfg, "").unwrap();
11167
    assert_eq!(
11168
        Config::load(Some(&user), &repo_cfg).unwrap().author_key,
11169
        Some(old),
11170
        "no author.for: the note is ignored"
11171
    );
11172
    fs::write(
11173
        &user,
11174
        format!(
11175
            "author.key = \"{}\"\nauthor.for = \"andymccall\"\n",
11176
            old.to_hex()
11177
        ),
11178
    )
11179
    .unwrap();
11180
    assert_eq!(
11181
        Config::load(Some(&user), &repo_cfg).unwrap().author_key,
11182
        Some(new)
11183
    );
11184
    fs::write(&repo_cfg, format!("author.key = \"{}\"\n", pin.to_hex())).unwrap();
11185
    assert_eq!(
11186
        Config::load(Some(&user), &repo_cfg).unwrap().author_key,
11187
        Some(pin),
11188
        "a repository's pin wins"
11189
    );
11190
}