OXYGENHUB
◆ v0.6.0 oxygen / crates / oxy-core / src / repo / tests.rs
396.6 KiB · Rust · last changed Depth 0 takes no change, and a checkpoint is gathered in parallel (refs #137) 11 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
#[test]
239
fn concurrent_edits_conflict_and_can_be_resolved() {
240
    hermetic();
241
    let (dir, repo, h1, h2, h3) = conflicted_repo();
242
    let root = dir.path();
243
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
244
    assert_eq!(heads, [h2, h3].into_iter().collect());
245
    let st = repo.load_state(&[h2, h3]).unwrap();
246
    assert!(st.materialize().is_conflicted());
247
248
    // Checking out main writes markers.
249
    let r = repo
250
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
251
        .unwrap();
252
    assert!(r.conflicted);
253
    let marked = fs::read_to_string(root.join("f.txt")).unwrap();
254
    assert!(
255
        marked.starts_with("a\n<<<<<<< oxy conflict 1 of 1"),
256
        "{marked}"
257
    );
258
    assert!(
259
        marked.contains("B\n") && marked.contains("X\n") && marked.ends_with("end\nc\n"),
260
        "{marked}"
261
    );
262
    assert!(has_conflict_markers(marked.as_bytes()));
263
    // Untouched markers: clean working copy; commit has nothing to do.
264
    let s = repo.snapshot("status").unwrap();
265
    assert!(s.statuses.is_empty());
266
    assert!(!s.resolves);
267
268
    // Partially edited file that still has markers cannot be committed.
269
    write(root, "f.txt", marked.replace("B\n", "BB\n").as_bytes());
270
    let s = repo.snapshot("status").unwrap();
271
    assert_eq!(
272
        statuses(&s),
273
        vec![("f.txt".into(), ChangeStatus::ConflictEdited)]
274
    );
275
    assert!(repo.commit("no", &[]).is_err());
276
277
    // Resolve by keeping one side and adding a line elsewhere.
278
    write(root, "f.txt", b"a\nX\nc\nd\n");
279
    let s = repo.snapshot("status").unwrap();
280
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
281
    assert!(s.resolves);
282
    let h4 = repo.commit("resolve", &[]).unwrap();
283
    let c4 = repo.store().get_change(&h4).unwrap();
284
    assert_eq!(c4.kind, ChangeKind::Resolution);
285
    let mut want = vec![h1, h2, h3];
286
    want.sort();
287
    assert_eq!(
288
        c4.deps, want,
289
        "a resolution depends on exactly the contributors and what it references"
290
    );
291
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h4]);
292
    let snap = repo.load_state(&[h4]).unwrap().materialize();
293
    assert!(!snap.is_conflicted());
294
    assert!(
295
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
296
    );
297
    assert!(!repo.snapshot("status").unwrap().changed);
298
    // A peer holding only h2 and h3 and receiving h4 sees the same result,
299
    // whatever order the changes arrive in.
300
    let mut st = State::new();
301
    for h in [h4, h3, h1, h2] {
302
        st.add_unchecked(repo.store().get_change(&h).unwrap());
303
    }
304
    st.validate().unwrap();
305
    assert!(
306
        matches!(&st.materialize().files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
307
    );
308
}
309
310
/// oxygen#118 (Metal Gear): a resolution commits by paths, leaving other
311
/// work uncommitted, so long as it takes every file it resolves; and
312
/// `amend PATHS` folds only those paths into the head.
313
#[test]
314
fn resolutions_and_amends_take_paths() {
315
    hermetic();
316
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
317
    let root = dir.path();
318
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
319
        .unwrap();
320
    // The conflict resolved, and other work beside it.
321
    write(root, "f.txt", b"a\nX\nc\n");
322
    write(root, "notes.txt", b"pending\n");
323
    let s = repo.snapshot("status").unwrap();
324
    assert!(s.resolves);
325
    let err = repo
326
        .commit_selection_partial("resolve", &[], &Selection::Paths(vec!["notes.txt".into()]))
327
        .unwrap_err()
328
        .to_string();
329
    assert!(
330
        err.contains("takes every file it resolves") && err.contains("f.txt"),
331
        "{err}"
332
    );
333
    let (h4, partial) = repo
334
        .commit_selection_partial("resolve", &[], &Selection::Paths(vec!["f.txt".into()]))
335
        .unwrap();
336
    assert!(partial);
337
    assert_eq!(
338
        repo.store().get_change(&h4).unwrap().kind,
339
        ChangeKind::Resolution
340
    );
341
    assert!(!repo
342
        .load_state(&[h4])
343
        .unwrap()
344
        .materialize()
345
        .is_conflicted());
346
    let s = repo.snapshot("status").unwrap();
347
    assert_eq!(
348
        statuses(&s),
349
        vec![("notes.txt".into(), ChangeStatus::Added)],
350
        "the other work waits"
351
    );
352
353
    // amend PATHS: only those paths join the head; it keeps its ChangeId.
354
    // On the resolution, so the bookmark has one head to amend.
355
    let h5 = repo.commit("notes", &[h4]).unwrap();
356
    let id5 = repo.store().get_change(&h5).unwrap().change_id;
357
    write(root, "notes.txt", b"pending\nmore\n");
358
    write(root, "other.txt", b"later\n");
359
    let h6 = repo
360
        .amend_paths(Some("notes, amended"), &["notes.txt".into()])
361
        .unwrap();
362
    let c6 = repo.store().get_change(&h6).unwrap();
363
    assert_eq!((c6.change_id, c6.message.as_str()), (id5, "notes, amended"));
364
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h6]);
365
    let snap6 = repo.load_state(&[h6]).unwrap().materialize();
366
    assert!(
367
        matches!(&snap6.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"pending\nmore\n")
368
    );
369
    assert!(
370
        !snap6.files.contains_key("other.txt"),
371
        "other.txt stays out"
372
    );
373
    let s = repo.snapshot("status").unwrap();
374
    assert_eq!(
375
        statuses(&s),
376
        vec![("other.txt".into(), ChangeStatus::Added)]
377
    );
378
}
379
380
#[test]
381
fn resolution_may_keep_both_sides_or_neither() {
382
    hermetic();
383
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
384
    let root = dir.path();
385
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
386
        .unwrap();
387
    // Keep both sides in a chosen order.
388
    write(root, "f.txt", b"a\nX\nB\nc\n");
389
    let h = repo.commit("both", &[]).unwrap();
390
    let snap = repo.load_state(&[h]).unwrap().materialize();
391
    assert!(!snap.is_conflicted());
392
    assert!(
393
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n")
394
    );
395
    // Undo and instead drop the whole region.
396
    repo.undo().unwrap();
397
    write(root, "f.txt", b"a\nc\n");
398
    let h = repo.commit("neither", &[]).unwrap();
399
    let snap = repo.load_state(&[h]).unwrap().materialize();
400
    assert!(!snap.is_conflicted());
401
    assert!(
402
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n")
403
    );
404
}
405
406
#[test]
407
fn name_conflict_resolved_by_removing_a_candidate() {
408
    hermetic();
409
    let dir = tempfile::tempdir().unwrap();
410
    let root = dir.path();
411
    let repo = Repo::init(root).unwrap();
412
    write(root, "keep.txt", b"k\n");
413
    let h1 = repo.commit("base", &[]).unwrap();
414
    write(root, "new.txt", b"one\n");
415
    repo.commit("one", &[]).unwrap();
416
    repo.checkout(&[h1], false, "checkout").unwrap();
417
    write(root, "new.txt", b"two\n");
418
    repo.commit("two", &[]).unwrap();
419
    let r = repo
420
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
421
        .unwrap();
422
    assert!(r.conflicted);
423
    assert!(
424
        root.join("new.txt.oxy-conflict-1").exists()
425
            && root.join("new.txt.oxy-conflict-2").exists()
426
    );
427
    assert!(!root.join("new.txt").exists());
428
    // Candidate numbering follows change-hash order, so pick by content:
429
    // keep the "two" candidate under the real name and drop the other.
430
    let (keep, drop) = if fs::read(root.join("new.txt.oxy-conflict-1")).unwrap() == b"two\n" {
431
        (1, 2)
432
    } else {
433
        (2, 1)
434
    };
435
    fs::remove_file(root.join(format!("new.txt.oxy-conflict-{drop}"))).unwrap();
436
    fs::rename(
437
        root.join(format!("new.txt.oxy-conflict-{keep}")),
438
        root.join("new.txt"),
439
    )
440
    .unwrap();
441
    let h = repo.commit("pick two", &[]).unwrap();
442
    assert_eq!(
443
        repo.store().get_change(&h).unwrap().kind,
444
        ChangeKind::Resolution
445
    );
446
    // The resolution does not touch keep.txt, so it does not depend on h1;
447
    // the bookmark keeps both as heads and their union is the state.
448
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
449
    assert_eq!(heads, [h1, h].into_iter().collect());
450
    let snap = repo
451
        .load_state(&repo.bookmark_heads().unwrap())
452
        .unwrap()
453
        .materialize();
454
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
455
    assert_eq!(
456
        snap.files.keys().cloned().collect::<Vec<_>>(),
457
        ["keep.txt", "new.txt"]
458
    );
459
    assert!(
460
        matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n")
461
    );
462
}
463
464
/// Each of two bookmarks adds `path` (a file written by `side` on each)
465
/// from the same base, and the second is merged into the first. Returns
466
/// the repository on `main`, the merge's heads, and the three changes.
467
fn merged_additions(
468
    side: impl Fn(&Path, bool),
469
) -> (tempfile::TempDir, Repo, Vec<ChangeHash>, [ChangeHash; 3]) {
470
    let dir = tempfile::tempdir().unwrap();
471
    let root = dir.path().to_path_buf();
472
    let mut repo = Repo::init(&root).unwrap();
473
    write(&root, "keep.txt", b"k\n");
474
    let h1 = repo.commit("base", &[]).unwrap();
475
    repo.bookmark_create("side", None).unwrap();
476
    side(&root, false);
477
    let ha = repo.commit("add on main", &[]).unwrap();
478
    repo.bookmark_switch("side", false).unwrap();
479
    side(&root, true);
480
    let hb = repo.commit("add on side", &[]).unwrap();
481
    repo.bookmark_switch("main", false).unwrap();
482
    let m = repo.merge("side").unwrap();
483
    assert!(m.changed && m.checked_out);
484
    (dir, repo, m.heads, [h1, ha, hb])
485
}
486
487
fn conflict_copies(root: &Path) -> Vec<String> {
488
    let mut out: Vec<String> = fs::read_dir(root)
489
        .unwrap()
490
        .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
491
        .filter(|n| n.contains(".oxy-conflict-"))
492
        .collect();
493
    out.sort();
494
    out
495
}
496
497
/// The same path added on two bookmarks with identical content is one
498
/// file after the merge (oxygen#101): no conflict, nothing to resolve,
499
/// nothing recorded; and editing or removing it later keeps it one.
500
#[test]
501
fn identical_additions_unify_on_merge() {
502
    hermetic();
503
    let (dir, repo, heads, [h1, ha, hb]) =
504
        merged_additions(|root, _| write(root, "x.txt", b"same\nlines\n"));
505
    let root = dir.path();
506
    // The tree graph has the name conflict; every reader sees one file.
507
    let st = repo.load_state(&heads).unwrap();
508
    assert!(st
509
        .tree()
510
        .view()
511
        .conflicts
512
        .iter()
513
        .any(|c| matches!(c, crate::tree::TreeConflict::Name { .. })));
514
    let snap = st.materialize();
515
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
516
    assert_eq!(
517
        snap.files.keys().cloned().collect::<Vec<_>>(),
518
        ["keep.txt", "x.txt"]
519
    );
520
    assert!(
521
        matches!(&snap.files["x.txt"].content, FileContent::Text { bytes, .. } if bytes == b"same\nlines\n")
522
    );
523
    assert_eq!(snap.tree.unified.len(), 1);
524
    // On disk once, the working copy clean, nothing to commit.
525
    assert_eq!(fs::read(root.join("x.txt")).unwrap(), b"same\nlines\n");
526
    assert!(
527
        conflict_copies(root).is_empty(),
528
        "{:?}",
529
        conflict_copies(root)
530
    );
531
    let s = repo.snapshot("status").unwrap();
532
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
533
    assert!(!s.changed && !s.resolves);
534
    assert!(!s.base_snapshot.is_conflicted());
535
    assert!(s.wc.tree_ops.is_empty() && s.wc.edits.is_empty());
536
    let json = repo.status_json(&s).unwrap();
537
    assert!(json.contains("\"conflicted\":false"), "{json}");
538
    assert!(repo.commit("nothing", &[]).is_err());
539
    assert_eq!(repo.file_at("x.txt", None).unwrap(), b"same\nlines\n");
540
    // A peer holding the same changes, added in another order, agrees.
541
    let mut peer = State::new();
542
    for h in [hb, ha, h1] {
543
        peer.add_unchecked(repo.store().get_change(&h).unwrap());
544
    }
545
    peer.validate().unwrap();
546
    let ps = peer.materialize();
547
    assert!(!ps.is_conflicted());
548
    assert_eq!(ps.tree.entries["x.txt"], snap.tree.entries["x.txt"]);
549
    assert_eq!(ps.tree.unified, snap.tree.unified);
550
    // The file's history is both additions.
551
    let log: Vec<ChangeHash> = repo
552
        .log_for_path("x.txt")
553
        .unwrap()
554
        .iter()
555
        .map(|e| e.hash)
556
        .collect();
557
    assert!(log.contains(&ha) && log.contains(&hb), "{log:?}");
558
559
    // Edited and committed: one file still, the duplicate retired with it.
560
    write(root, "x.txt", b"same\nedited\n");
561
    let s = repo.snapshot("status").unwrap();
562
    assert_eq!(statuses(&s), vec![("x.txt".into(), ChangeStatus::Modified)]);
563
    let he = repo.commit("edit x", &[]).unwrap();
564
    let c = repo.store().get_change(&he).unwrap();
565
    assert_eq!(c.kind, ChangeKind::Normal);
566
    let (dup, _) = snap.tree.unified.iter().next().unwrap();
567
    assert!(
568
        c.tree_ops
569
            .iter()
570
            .any(|o| matches!(o, TreeOp::RemoveNode { node, .. } if node == dup)),
571
        "{:?}",
572
        c.tree_ops
573
    );
574
    let d = repo.describe_change(&he).unwrap();
575
    assert!(!d.contains("D x.txt"), "{d}");
576
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
577
    assert!(
578
        st.tree().view().conflicts.is_empty(),
579
        "nothing left to unify"
580
    );
581
    let snap = st.materialize();
582
    assert!(!snap.is_conflicted());
583
    assert!(
584
        matches!(&snap.files["x.txt"].content, FileContent::Text { bytes, .. } if bytes == b"same\nedited\n")
585
    );
586
    assert!(!repo.snapshot("status").unwrap().changed);
587
588
    // Removed and committed: gone.
589
    fs::remove_file(root.join("x.txt")).unwrap();
590
    repo.commit("drop x", &[]).unwrap();
591
    let snap = repo
592
        .load_state(&repo.bookmark_heads().unwrap())
593
        .unwrap()
594
        .materialize();
595
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
596
    assert_eq!(snap.files.keys().cloned().collect::<Vec<_>>(), ["keep.txt"]);
597
    assert!(!root.join("x.txt").exists());
598
}
599
600
/// Removing, renaming, or committing just the path of a unified file
601
/// retires its duplicate with it, so the conflict never comes back.
602
#[test]
603
fn unified_additions_stay_one_when_removed_renamed_or_committed_alone() {
604
    hermetic();
605
    let add = |root: &Path, _: bool| write(root, "x.txt", b"same\n");
606
    for how in ["remove", "rename", "path", "hunk"] {
607
        let (dir, repo, _, _) = merged_additions(add);
608
        let root = dir.path();
609
        match how {
610
            "remove" => fs::remove_file(root.join("x.txt")).unwrap(),
611
            "rename" => fs::rename(root.join("x.txt"), root.join("y.txt")).unwrap(),
612
            _ => {
613
                write(root, "x.txt", b"same\nmore\n");
614
                write(root, "other.txt", b"o\n");
615
            }
616
        }
617
        let s = repo.snapshot("status").unwrap();
618
        let h = match how {
619
            "path" => repo
620
                .commit_selection("x alone", &[], &Selection::Paths(vec!["x.txt".into()]))
621
                .unwrap(),
622
            "hunk" => {
623
                let (_, hunks) = repo.hunks().unwrap();
624
                // The duplicate's retirement is no hunk of its own.
625
                assert!(hunks.iter().all(|h| !h.text.starts_with("D ")), "{hunks:?}");
626
                let x: Vec<usize> = hunks
627
                    .iter()
628
                    .filter(|h| h.path == "x.txt")
629
                    .map(|h| h.index)
630
                    .collect();
631
                assert!(!x.is_empty());
632
                repo.commit_selection("x hunks", &[], &Selection::Hunks(x))
633
                    .unwrap()
634
            }
635
            _ => repo.commit(how, &[]).unwrap(),
636
        };
637
        assert!(!s.base_snapshot.is_conflicted());
638
        let heads = repo.bookmark_heads().unwrap();
639
        assert!(heads.contains(&h));
640
        let snap = repo.load_state(&heads).unwrap().materialize();
641
        assert!(!snap.is_conflicted(), "{how}: {:?}", snap.tree.conflicts);
642
        let want: &[&str] = match how {
643
            "remove" => &["keep.txt"],
644
            "rename" => &["keep.txt", "y.txt"],
645
            _ => &["keep.txt", "x.txt"],
646
        };
647
        assert_eq!(
648
            snap.files.keys().cloned().collect::<Vec<_>>(),
649
            want,
650
            "{how}"
651
        );
652
        assert!(conflict_copies(root).is_empty(), "{how}");
653
    }
654
}
655
656
/// The same path added with different content, or a different mode, is a
657
/// name conflict as before.
658
#[test]
659
fn additions_that_differ_still_conflict() {
660
    hermetic();
661
    #[cfg(unix)]
662
    use std::os::unix::fs::PermissionsExt;
663
    let content =
664
        |root: &Path, side: bool| write(root, "x.txt", if side { b"two\n" } else { b"one\n" });
665
    let mode = |root: &Path, side: bool| {
666
        write(root, "x.txt", b"same\n");
667
        #[cfg(unix)]
668
        if side {
669
            fs::set_permissions(root.join("x.txt"), fs::Permissions::from_mode(0o755)).unwrap();
670
        }
671
    };
672
    let check = |what: &str, side: &dyn Fn(&Path, bool)| {
673
        let (dir, repo, heads, _) = merged_additions(side);
674
        let snap = repo.load_state(&heads).unwrap().materialize();
675
        assert!(snap.tree.unified.is_empty(), "{what}");
676
        assert!(
677
            snap.tree.conflicts.iter().any(
678
                |c| matches!(c, crate::tree::TreeConflict::Name { name, .. } if name == "x.txt")
679
            ),
680
            "{what}: {:?}",
681
            snap.tree.conflicts
682
        );
683
        assert_eq!(
684
            conflict_copies(dir.path()),
685
            ["x.txt.oxy-conflict-1", "x.txt.oxy-conflict-2"],
686
            "{what}"
687
        );
688
        assert!(!dir.path().join("x.txt").exists(), "{what}");
689
    };
690
    check("content", &content);
691
    #[cfg(unix)]
692
    check("mode", &mode);
693
    #[cfg(not(unix))]
694
    let _ = mode;
695
}
696
697
/// The same subrepo at the same pin, added on two bookmarks, is one
698
/// subrepo after the merge (oxygen#101), as is the identical
699
/// `.oxymodules` beside it.
700
#[test]
701
fn the_same_subrepo_added_on_two_bookmarks_unifies() {
702
    hermetic();
703
    let dir = tempfile::tempdir().unwrap();
704
    let root = dir.path();
705
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
706
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
707
    let lib = Repo::clone(&lib_url, &root.join("lib"))
708
        .unwrap()
709
        .with_home(root.join("home"));
710
    write(&root.join("lib"), "lib.txt", b"v1\n");
711
    lib.commit("lib v1", &[]).unwrap();
712
    assert!(lib.push("origin", false).unwrap()[0].ok);
713
    let _ = lib_origin;
714
715
    let app_dir = root.join("app");
716
    let mut app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
717
    write(&app_dir, "main.txt", b"app\n");
718
    app.commit("base", &[]).unwrap();
719
    app.bookmark_create("side", None).unwrap();
720
    app.submodule_add(&lib_url, "rstar-api", None).unwrap();
721
    let modules = fs::read(app_dir.join(".oxymodules")).unwrap();
722
    app.commit("rstar-api on main", &[]).unwrap();
723
    // On the other bookmark the nested repository is still there (it is
724
    // never deleted); registering it again adds it at the same pin.
725
    app.bookmark_switch("side", false).unwrap();
726
    assert!(app_dir.join("rstar-api/.oxy").is_dir());
727
    write(&app_dir, ".oxymodules", &modules);
728
    let s = app.snapshot("status").unwrap();
729
    assert_eq!(
730
        statuses(&s),
731
        vec![
732
            (".oxymodules".into(), ChangeStatus::Added),
733
            ("rstar-api".into(), ChangeStatus::Added)
734
        ]
735
    );
736
    app.commit("rstar-api on side", &[]).unwrap();
737
    app.bookmark_switch("main", false).unwrap();
738
739
    let m = app.merge("side").unwrap();
740
    assert!(m.changed && m.checked_out);
741
    let snap = app.load_state(&m.heads).unwrap().materialize();
742
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
743
    assert_eq!(snap.tree.unified.len(), 2);
744
    assert_eq!(snap.files["rstar-api"].kind, NodeKind::Subrepo);
745
    assert!(conflict_copies(&app_dir).is_empty());
746
    let s = app.snapshot("status").unwrap();
747
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
748
    assert!(!s.base_snapshot.is_conflicted());
749
    assert_eq!(
750
        fs::read_to_string(app_dir.join("rstar-api/lib.txt")).unwrap(),
751
        "v1\n"
752
    );
753
}
754
755
#[test]
756
fn identities_and_signed_commits() {
757
    hermetic();
758
    let dir = tempfile::tempdir().unwrap();
759
    let root = dir.path();
760
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
761
    write(root, "a.txt", b"a\n");
762
    let h0 = repo.commit("unsigned", &[]).unwrap();
763
    assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
764
    assert_eq!(
765
        repo.store().get_change(&h0).unwrap().author,
766
        ObjectRef::ZERO
767
    );
768
769
    let (key, id) = repo
770
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
771
        .unwrap();
772
    assert_eq!(id.hash(), key);
773
    assert_eq!(repo.config.author_key, Some(key));
774
    // Config survives reopen; the secret key is found again.
775
    let reopened = Repo::open(root).unwrap().with_home(root.join("home"));
776
    assert_eq!(reopened.config.author_key, Some(key));
777
    assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
778
779
    // Default core.sign = seal: commits carry the author but no signature.
780
    write(root, "a.txt", b"a\nb\n");
781
    let h1 = repo.commit("authored", &[]).unwrap();
782
    assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
783
    assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
784
    // Signing later works too.
785
    repo.sign_change(&h1).unwrap();
786
    assert!(
787
        matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
788
    );
789
790
    repo.config.set("core.sign", "change").unwrap();
791
    repo.save_config().unwrap();
792
    write(root, "a.txt", b"a\nb\nc\n");
793
    let h2 = repo.commit("signed", &[]).unwrap();
794
    assert_eq!(
795
        repo.verify_change(&h2).unwrap(),
796
        SignatureStatus::Valid {
797
            key,
798
            name: "Ada".into(),
799
            email: "[email protected]".into(),
800
            sealed: false,
801
            revoked: false
802
        }
803
    );
804
805
    // A signature by a key that is not the author or a delegate is rejected
806
    // when the change names an author; an anonymous change (made before any
807
    // identity, author zero) is adopted by whoever signs it (spec §14.4).
808
    let other = SecretKey::generate();
809
    let other_id = other.identity("Mallory", "[email protected]", 0);
810
    let other_key = repo.store().put_identity(&other_id).unwrap();
811
    write(root, "a.txt", b"a\nb\nc\nd\n");
812
    repo.config.set("core.sign", "seal").unwrap();
813
    let h3 = repo.commit("ada's, unsigned", &[]).unwrap();
814
    let forged = other.sign(Domain::Change, &other_key, &h3);
815
    repo.store().put_signature(&h3, &forged).unwrap();
816
    assert!(
817
        matches!(repo.verify_change(&h3).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author"))
818
    );
819
    let adopted = other.sign(Domain::Change, &other_key, &h0);
820
    repo.store().put_signature(&h0, &adopted).unwrap();
821
    assert!(
822
        matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Valid { name, .. } if name == "Mallory")
823
    );
824
825
    // Tampering with the stored signature invalidates it.
826
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
827
    sig.ed[0] ^= 1;
828
    repo.store().put_signature(&h2, &sig).unwrap();
829
    assert!(matches!(
830
        repo.verify_change(&h2).unwrap(),
831
        SignatureStatus::Invalid(_)
832
    ));
833
834
    // Without the secret key, signing at commit fails cleanly.
835
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
836
    write(root, "a.txt", b"z\n");
837
    assert!(no_keys.commit("cannot sign", &[]).is_err());
838
}
839
840
#[test]
841
fn checkout_moves_the_working_copy() {
842
    hermetic();
843
    let dir = tempfile::tempdir().unwrap();
844
    let root = dir.path();
845
    let repo = Repo::init(root).unwrap();
846
    write(root, "a.txt", b"one\n");
847
    write(root, "sub/deep/b.txt", b"b\n");
848
    let h1 = repo.commit("first", &[]).unwrap();
849
    write(root, "a.txt", b"two\n");
850
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
851
    write(root, "bin.dat", &[0, 1, 2, 3]);
852
    let h2 = repo.commit("second", &[]).unwrap();
853
854
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
855
    assert_eq!(
856
        r,
857
        CheckoutReport {
858
            written: 2,
859
            removed: 1,
860
            removed_paths: vec!["bin.dat".into()],
861
            conflicted: false,
862
            notes: vec![],
863
            lacks: 1,
864
        }
865
    );
866
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
867
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
868
    assert!(!root.join("bin.dat").exists());
869
    let (_, wc) = repo.working_copy().unwrap();
870
    assert_eq!(wc.deps, vec![h1]);
871
    assert!(
872
        !repo.snapshot("status").unwrap().changed,
873
        "checkout leaves a clean working copy"
874
    );
875
    // The bookmark still points at h2.
876
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
877
878
    // Dirty working copy refuses without --discard.
879
    write(root, "a.txt", b"dirty\n");
880
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
881
    let r = repo
882
        .checkout(&[h2], true, "oxy checkout --discard")
883
        .unwrap();
884
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
885
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
886
    assert!(!root.join("sub").exists(), "empty directories are pruned");
887
    assert_eq!(r.removed, 1);
888
    assert!(!repo.snapshot("status").unwrap().changed);
889
890
    // Refuses to write through a symlinked directory.
891
    #[cfg(unix)]
892
    {
893
        fs::remove_dir_all(root.join("sub")).ok();
894
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
895
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
896
    }
897
}
898
899
#[test]
900
fn large_files_are_chunked_and_read_back() {
901
    hermetic();
902
    let dir = tempfile::tempdir().unwrap();
903
    let repo = Repo::init(dir.path()).unwrap();
904
    let mut big = vec![0u8; 700 * 1024];
905
    for (i, b) in big.iter_mut().enumerate() {
906
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
907
    }
908
    let r = repo.store_blob(&big).unwrap();
909
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
910
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
911
    assert_eq!(repo.read_blob(&r).unwrap(), big);
912
    assert_eq!(Repo::blob_ref(&big), r);
913
}
914
915
#[test]
916
fn clone_push_pull_with_seals_and_attestations() {
917
    hermetic();
918
    let dir = tempfile::tempdir().unwrap();
919
    let root = dir.path();
920
    let origin_path = root.join("origin");
921
    let origin = Repo::init(&origin_path).unwrap();
922
    let origin_url = origin_path.to_string_lossy().to_string();
923
924
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
925
    let mut a = Repo::clone(&origin_url, &root.join("a"))
926
        .unwrap()
927
        .with_home(root.join("home-a"));
928
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
929
    let (key_a, _) = a
930
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
931
        .unwrap();
932
    write(&root.join("a"), "f.txt", b"a\n");
933
    let h1 = a.commit("first", &[]).unwrap();
934
    let results = a.push("origin", false).unwrap();
935
    origin.refresh().unwrap();
936
    assert!(results[0].ok, "{}", results[0].reason);
937
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
938
    // The change was sealed at push and the reference attested.
939
    assert!(
940
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
941
    );
942
    assert_eq!(
943
        origin.verify_change(&h1).unwrap(),
944
        SignatureStatus::Unsigned
945
    );
946
    let serial_of = |att: &SignedAttest| match att.attest.body {
947
        AttestBody::Ref { serial, .. } => serial,
948
        _ => unreachable!(),
949
    };
950
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
951
    // A bookmark new to the remote starts at the clock (past any deleted
952
    // namesake's serial); later updates count up from there.
953
    let first = serial_of(&att);
954
    assert!(first > 1_000_000_000_000, "{first}");
955
    let again = a.push("origin", false).unwrap();
956
    origin.refresh().unwrap();
957
    assert!(again[0].ok && again[0].reason.contains("up to date"));
958
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
959
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
960
961
    // B clones and sees the file and the seal.
962
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
963
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
964
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
965
    assert!(matches!(
966
        b.authenticate_change(&h1).unwrap(),
967
        SignatureStatus::Valid { sealed: true, .. }
968
    ));
969
970
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
971
    write(&root.join("b"), "f.txt", b"a\nb\n");
972
    let h2 = b.commit("second", &[]).unwrap();
973
    assert!(b.push("origin", false).unwrap()[0].ok);
974
    origin.refresh().unwrap();
975
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
976
977
    // A commits an independent change; push is refused until A pulls.
978
    write(&root.join("a"), "g.txt", b"g\n");
979
    let h3 = a.commit("third", &[]).unwrap();
980
    assert!(a.push("origin", false).is_err());
981
    let pr = a.pull("origin").unwrap();
982
    assert!(pr.changed && pr.checked_out);
983
    let mut want = vec![h2, h3];
984
    want.sort();
985
    assert_eq!(pr.heads, want);
986
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
987
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
988
    let results = a.push("origin", false).unwrap();
989
    origin.refresh().unwrap();
990
    assert!(results[0].ok, "{}", results[0].reason);
991
    let mut origin_heads = origin.bookmark_heads().unwrap();
992
    origin_heads.sort();
993
    assert_eq!(origin_heads, want);
994
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
995
    assert_eq!(serial_of(&att), first + 1);
996
997
    // B pulls and ends up identical.
998
    let pr = b.pull("origin").unwrap();
999
    assert_eq!(pr.heads, want);
1000
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
1001
    assert!(!b.snapshot("status").unwrap().changed);
1002
1003
    // Concurrent edits of the same line: the union is a reified conflict.
1004
    write(&root.join("a"), "f.txt", b"a\nA\n");
1005
    a.commit("a-edit", &[]).unwrap();
1006
    a.push("origin", false).unwrap();
1007
    origin.refresh().unwrap();
1008
    write(&root.join("b"), "f.txt", b"a\nB\n");
1009
    b.commit("b-edit", &[]).unwrap();
1010
    let pr = b.pull("origin").unwrap();
1011
    assert!(pr.changed && pr.checked_out);
1012
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
1013
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
1014
    write(&root.join("b"), "f.txt", b"a\nAB\n");
1015
    let hr = b.commit("resolve", &[]).unwrap();
1016
    assert_eq!(
1017
        b.store().get_change(&hr).unwrap().kind,
1018
        ChangeKind::Resolution
1019
    );
1020
    assert!(b.push("origin", false).unwrap()[0].ok);
1021
    origin.refresh().unwrap();
1022
    a.pull("origin").unwrap();
1023
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
1024
    // The resolution depends on the conflicting edits, but nothing depends
1025
    // on "third" (it only added g.txt), so it stays a head beside it.
1026
    let mut want = vec![hr, h3];
1027
    want.sort();
1028
    assert_eq!(a.bookmark_heads().unwrap(), want);
1029
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
1030
}
1031
1032
#[test]
1033
fn receive_push_rejects_bad_updates() {
1034
    hermetic();
1035
    let dir = tempfile::tempdir().unwrap();
1036
    let root = dir.path();
1037
    let origin = Repo::init(&root.join("origin")).unwrap();
1038
    let url = root.join("origin").to_string_lossy().to_string();
1039
    let mut a = Repo::clone(&url, &root.join("a"))
1040
        .unwrap()
1041
        .with_home(root.join("home"));
1042
    let (key, _) = a
1043
        .create_identity("Ada", "a@b", IdentityScope::Repo)
1044
        .unwrap();
1045
    write(&root.join("a"), "f.txt", b"x\n");
1046
    let h1 = a.commit("one", &[]).unwrap();
1047
    assert!(a.push("origin", false).unwrap()[0].ok);
1048
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
1049
    let s1 = origin
1050
        .store()
1051
        .put_state(&StateObject::new(vec![h1]))
1052
        .unwrap();
1053
1054
    // Missing head.
1055
    let ghost = origin
1056
        .store()
1057
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
1058
        .unwrap();
1059
    let r = origin
1060
        .receive_push(
1061
            Bundle::default(),
1062
            vec![RefUpdate {
1063
                name: "main".into(),
1064
                old_state: s1,
1065
                new_state: ghost,
1066
                force: false,
1067
                attestation: None,
1068
            }],
1069
            None,
1070
            vec![],
1071
        )
1072
        .unwrap();
1073
    assert!(
1074
        !r[0].ok && r[0].reason.contains("missing"),
1075
        "{}",
1076
        r[0].reason
1077
    );
1078
1079
    // Stale old_state.
1080
    let r = origin
1081
        .receive_push(
1082
            Bundle::default(),
1083
            vec![RefUpdate {
1084
                name: "main".into(),
1085
                old_state: empty,
1086
                new_state: s1,
1087
                force: false,
1088
                attestation: None,
1089
            }],
1090
            None,
1091
            vec![],
1092
        )
1093
        .unwrap();
1094
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
1095
1096
    // Non-fast-forward without force is refused; with force it passes.
1097
    let r = origin
1098
        .receive_push(
1099
            Bundle::default(),
1100
            vec![RefUpdate {
1101
                name: "main".into(),
1102
                old_state: s1,
1103
                new_state: empty,
1104
                force: false,
1105
                attestation: None,
1106
            }],
1107
            None,
1108
            vec![],
1109
        )
1110
        .unwrap();
1111
    assert!(
1112
        !r[0].ok && r[0].reason.contains("fast-forward"),
1113
        "{}",
1114
        r[0].reason
1115
    );
1116
    let r = origin
1117
        .receive_push(
1118
            Bundle::default(),
1119
            vec![RefUpdate {
1120
                name: "main".into(),
1121
                old_state: s1,
1122
                new_state: empty,
1123
                force: true,
1124
                attestation: None,
1125
            }],
1126
            None,
1127
            vec![],
1128
        )
1129
        .unwrap();
1130
    assert!(r[0].ok);
1131
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
1132
1133
    // Attestation with a stale serial is a rollback and is refused.
1134
    let sa = a
1135
        .sign_attest(&Attest {
1136
            repo: a.id().unwrap(),
1137
            hlc: Hlc::now(),
1138
            body: AttestBody::Ref {
1139
                name: "main".into(),
1140
                old_state: empty,
1141
                new_state: s1,
1142
                serial: 1,
1143
            },
1144
        })
1145
        .unwrap();
1146
    let r = origin
1147
        .receive_push(
1148
            Bundle::default(),
1149
            vec![RefUpdate {
1150
                name: "main".into(),
1151
                old_state: empty,
1152
                new_state: s1,
1153
                force: false,
1154
                attestation: Some(sa.clone()),
1155
            }],
1156
            None,
1157
            vec![],
1158
        )
1159
        .unwrap();
1160
    assert!(
1161
        !r[0].ok && r[0].reason.contains("serial"),
1162
        "{}",
1163
        r[0].reason
1164
    );
1165
    // An attestation for a different update is refused too.
1166
    let sa2 = a
1167
        .sign_attest(&Attest {
1168
            repo: a.id().unwrap(),
1169
            hlc: Hlc::now(),
1170
            body: AttestBody::Ref {
1171
                name: "main".into(),
1172
                old_state: s1,
1173
                new_state: empty,
1174
                serial: 5,
1175
            },
1176
        })
1177
        .unwrap();
1178
    let r = origin
1179
        .receive_push(
1180
            Bundle::default(),
1181
            vec![RefUpdate {
1182
                name: "main".into(),
1183
                old_state: empty,
1184
                new_state: s1,
1185
                force: false,
1186
                attestation: Some(sa2),
1187
            }],
1188
            None,
1189
            vec![],
1190
        )
1191
        .unwrap();
1192
    assert!(
1193
        !r[0].ok && r[0].reason.contains("describe"),
1194
        "{}",
1195
        r[0].reason
1196
    );
1197
    let _ = key;
1198
}
1199
1200
#[test]
1201
fn user_config_supplies_defaults_and_clones_sign() {
1202
    hermetic();
1203
    let dir = tempfile::tempdir().unwrap();
1204
    let root = dir.path();
1205
    let home = root.join("home");
1206
    let origin = Repo::init(&root.join("origin")).unwrap();
1207
    let url = root.join("origin").to_string_lossy().to_string();
1208
1209
    // Identity at user scope: the repository file stays free of author keys.
1210
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
1211
    let (key, _) = a
1212
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1213
        .unwrap();
1214
    assert!(!a.config.repo_layer().contains_key("author.key"));
1215
    assert_eq!(a.config.author_key, Some(key));
1216
    assert!(home.join("config.toml").exists());
1217
    a.set_user_config("core.sign", "change").unwrap();
1218
    assert!(a.config.sign_changes);
1219
1220
    // Repository settings override user settings and are the only ones saved.
1221
    a.config.set("core.sign", "seal").unwrap();
1222
    a.save_config().unwrap();
1223
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
1224
    assert!(!again.config.sign_changes);
1225
    assert_eq!(again.config.author_key, Some(key));
1226
    assert_eq!(
1227
        read_config_file(&root.join("a/.oxy/config"))
1228
            .unwrap()
1229
            .get("core.sign")
1230
            .map(String::as_str),
1231
        Some("seal")
1232
    );
1233
1234
    // A fresh clone made by this user signs with the user-level identity,
1235
    // even though the clone's store has never seen the identity object.
1236
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
1237
    assert!(b.config.sign_changes);
1238
    write(&root.join("b"), "f.txt", b"f\n");
1239
    let h = b.commit("signed from a clone", &[]).unwrap();
1240
    assert!(
1241
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
1242
    );
1243
    assert!(b.push("origin", false).unwrap()[0].ok);
1244
    assert!(matches!(
1245
        origin.verify_change(&h).unwrap(),
1246
        SignatureStatus::Valid { .. }
1247
    ));
1248
}
1249
1250
#[test]
1251
fn format1_repositories_are_migrated_on_open() {
1252
    hermetic();
1253
    use crate::oplog::{Format1Op, Format1View};
1254
    let dir = tempfile::tempdir().unwrap();
1255
    let root = dir.path();
1256
    let repo = Repo::init(root).unwrap();
1257
    write(root, "a.txt", b"a\n");
1258
    let h1 = repo.commit("one", &[]).unwrap();
1259
    let (wc_hash, _) = repo.working_copy().unwrap();
1260
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
1261
    let mut v1 = Format1View::default();
1262
    v1.bookmarks.insert("main".into(), vec![]);
1263
    v1.workspaces.insert(repo.workspace(), wc_hash);
1264
    let init = Format1Op {
1265
        parents: vec![],
1266
        hlc: Hlc::default(),
1267
        command: "oxy init".into(),
1268
        view: v1.clone(),
1269
    };
1270
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
1271
    v1.bookmarks.insert("main".into(), vec![h1]);
1272
    let commit = Format1Op {
1273
        parents: vec![init_ref],
1274
        hlc: Hlc::default(),
1275
        command: "oxy commit".into(),
1276
        view: v1,
1277
    };
1278
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
1279
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
1280
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
1281
    drop(repo);
1282
1283
    let repo = Repo::open(root).unwrap();
1284
    assert_eq!(
1285
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
1286
        FORMAT_LINE
1287
    );
1288
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
1289
    let ops = repo.op_log().unwrap();
1290
    assert_eq!(
1291
        ops.iter()
1292
            .map(|(_, o)| o.command.as_str())
1293
            .collect::<Vec<_>>(),
1294
        ["oxy commit", "oxy init"]
1295
    );
1296
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
1297
    assert!(!repo.snapshot("status").unwrap().changed);
1298
    // Reopening again is a no-op.
1299
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
1300
}
1301
1302
#[test]
1303
fn undo_skips_snapshot_operations() {
1304
    hermetic();
1305
    let dir = tempfile::tempdir().unwrap();
1306
    let root = dir.path();
1307
    let repo = Repo::init(root).unwrap();
1308
    write(root, "a.txt", b"a\n");
1309
    let h1 = repo.commit("a", &[]).unwrap();
1310
    // A later command snapshots new edits on top of the commit.
1311
    write(root, "b.txt", b"b\n");
1312
    let s = repo.snapshot("oxy status").unwrap();
1313
    assert!(s.changed);
1314
    assert!(repo.head_op().unwrap().1.is_snapshot());
1315
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
1316
    // Undo must undo the commit, not the snapshot.
1317
    repo.undo().unwrap();
1318
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
1319
    let s = repo.snapshot("oxy status").unwrap();
1320
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
1321
    assert_eq!(
1322
        paths,
1323
        ["a.txt", "b.txt"],
1324
        "both files are back in the working copy"
1325
    );
1326
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
1327
    // Only snapshots remain above `init`, so there is nothing left to undo.
1328
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
1329
    assert!(repo.undo().is_err());
1330
}
1331
1332
#[test]
1333
fn independent_changes_commute_and_make_multiple_heads() {
1334
    hermetic();
1335
    let dir = tempfile::tempdir().unwrap();
1336
    let root = dir.path();
1337
    let repo = Repo::init(root).unwrap();
1338
    write(root, "a.txt", b"a\n");
1339
    let h1 = repo.commit("a", &[]).unwrap();
1340
    write(root, "b.txt", b"b\n");
1341
    let h2 = repo.commit("b", &[]).unwrap();
1342
    let c2 = repo.store().get_change(&h2).unwrap();
1343
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
1344
    let mut heads = repo.bookmark_heads().unwrap();
1345
    heads.sort();
1346
    let mut want = vec![h1, h2];
1347
    want.sort();
1348
    assert_eq!(heads, want);
1349
    // Editing a.txt depends on h1 only.
1350
    write(root, "a.txt", b"a\na2\n");
1351
    let h3 = repo.commit("a2", &[]).unwrap();
1352
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
1353
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1354
    assert_eq!(heads, [h2, h3].into_iter().collect());
1355
    // Explicit dependency.
1356
    write(root, "c.txt", b"c\n");
1357
    let h4 = repo.commit("c", &[h2]).unwrap();
1358
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
1359
}
1360
1361
#[test]
1362
fn mode_change_and_text_binary_switch() {
1363
    hermetic();
1364
    let dir = tempfile::tempdir().unwrap();
1365
    let root = dir.path();
1366
    let repo = Repo::init(root).unwrap();
1367
    write(root, "run.sh", b"#!/bin/sh\n");
1368
    repo.commit("add script", &[]).unwrap();
1369
    #[cfg(unix)]
1370
    {
1371
        use std::os::unix::fs::PermissionsExt;
1372
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1373
        let s = repo.snapshot("status").unwrap();
1374
        assert_eq!(
1375
            statuses(&s),
1376
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
1377
        );
1378
        let h = repo.commit("exec", &[]).unwrap();
1379
        let snap = repo.load_state(&[h]).unwrap().materialize();
1380
        assert!(snap.files["run.sh"].mode.exec);
1381
    }
1382
    // Text → binary → text.
1383
    write(root, "run.sh", b"\0binary");
1384
    let h = repo.commit("binary", &[]).unwrap();
1385
    let snap = repo.load_state(&[h]).unwrap().materialize();
1386
    assert!(snap.files["run.sh"].mode.opaque);
1387
    write(root, "run.sh", b"text again\n");
1388
    let h = repo.commit("text", &[]).unwrap();
1389
    let snap = repo.load_state(&[h]).unwrap().materialize();
1390
    assert!(!snap.files["run.sh"].mode.opaque);
1391
    assert!(
1392
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
1393
    );
1394
    assert!(!snap.is_conflicted());
1395
}
1396
1397
/// oxygen#87: a binary file given new contents and the executable bit in
1398
/// one commit kept the contents and lost the bit.
1399
#[cfg(unix)]
1400
#[test]
1401
fn a_binary_file_changed_and_made_executable_at_once_keeps_both() {
1402
    use std::os::unix::fs::PermissionsExt;
1403
    hermetic();
1404
    let dir = tempfile::tempdir().unwrap();
1405
    let root = dir.path();
1406
    let repo = Repo::init(root).unwrap();
1407
    write(root, "tool.exe", b"MZ\0one");
1408
    repo.commit("add", &[]).unwrap();
1409
    write(root, "tool.exe", b"MZ\0two");
1410
    fs::set_permissions(root.join("tool.exe"), fs::Permissions::from_mode(0o755)).unwrap();
1411
    let h = repo.commit("update and +x", &[]).unwrap();
1412
    let snap = repo.load_state(&[h]).unwrap().materialize();
1413
    let f = &snap.files["tool.exe"];
1414
    assert!(f.mode.opaque && f.mode.exec, "{:?}", f.mode);
1415
    assert!(
1416
        repo.snapshot("status").unwrap().statuses.is_empty(),
1417
        "nothing left to commit"
1418
    );
1419
}
1420
1421
/// Keyless step 4 (oxygenhub#241): an agent signing with a short-lived
1422
/// key whose certificate an issuer gave pushes when the policy grants its
1423
/// subject, and a fetch accepts what it attested; an expired certificate,
1424
/// or a subject the policy does not grant, may not move the bookmark.
1425
#[test]
1426
fn a_certified_key_pushes_under_a_subject_grant() {
1427
    use crate::cert::{Certificate, SignedCertificate};
1428
    use crate::identity::Scope;
1429
    hermetic();
1430
    let dir = tempfile::tempdir().unwrap();
1431
    let root = dir.path();
1432
    let _origin = Repo::init(&root.join("origin")).unwrap();
1433
    let url = root.join("origin").to_string_lossy().to_string();
1434
    let mut a = Repo::clone(&url, &root.join("a"))
1435
        .unwrap()
1436
        .with_home(root.join("home-a"));
1437
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1438
        .unwrap();
1439
    write(&root.join("a"), "a.txt", b"a\n");
1440
    a.commit("a", &[]).unwrap();
1441
    a.policy_init().unwrap();
1442
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1443
    let hub_sk = SecretKey::generate();
1444
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1445
    a.policy_grant_subject(
1446
        "agent:claude@ada",
1447
        hub.clone(),
1448
        Scope::CHANGES | Scope::REFS,
1449
        None,
1450
    )
1451
    .unwrap();
1452
    assert!(a
1453
        .push("origin", false)
1454
        .unwrap()
1455
        .iter()
1456
        .any(|r| r.name == "policy" && r.ok));
1457
1458
    let now = Hlc::now().wall_ms;
1459
    // An agent repository whose key the hub certified for `subject`, from
1460
    // `from` to `to`.
1461
    let agent = |name: &str, subject: &str, from: u64, to: u64| {
1462
        let mut r = Repo::clone(&url, &root.join(name))
1463
            .unwrap()
1464
            .with_home(root.join(format!("home-{name}")));
1465
        let (_, id) = r
1466
            .create_identity(name, "[email protected]", IdentityScope::User)
1467
            .unwrap();
1468
        let cert = SignedCertificate::sign(
1469
            Certificate {
1470
                key: id,
1471
                issuer: hub.hash(),
1472
                subject: subject.into(),
1473
                claims: vec![],
1474
                scope: Scope::CHANGES | Scope::REFS,
1475
                not_before: from,
1476
                expires: to,
1477
                grant: None,
1478
            },
1479
            &hub,
1480
            &hub_sk,
1481
        );
1482
        r.store().put_identity(&hub).unwrap();
1483
        r.store().put_certificate(&cert).unwrap();
1484
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1485
        r.commit("work", &[]).unwrap();
1486
        r
1487
    };
1488
1489
    let claude = agent("claude", "agent:claude@ada", now - 60_000, now + 600_000);
1490
    let r = claude.push("origin", false).unwrap();
1491
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1492
    // Ada's fetch accepts the bookmark the certified key attested.
1493
    a.pull("origin").unwrap();
1494
    assert!(a.bookmark_heads().unwrap().iter().any(|h| a
1495
        .store()
1496
        .get_change(h)
1497
        .map(|c| c.message == "work")
1498
        .unwrap_or(false)));
1499
1500
    // Step 4c: a host with an acceptor key records when it accepted the
1501
    // certified update and serves it; a fetch checks the certificate at
1502
    // that time only when the certificate's issuer signed it for exactly
1503
    // this attestation, else at the attestation's own time.
1504
    let host = Repo::open(&root.join("origin"))
1505
        .unwrap()
1506
        .with_acceptor(hub.clone(), hub_sk.clone());
1507
    let (attest_ref, sa) = host.latest_ref_attest("main").unwrap().unwrap();
1508
    host.record_acceptance(&attest_ref).unwrap();
1509
    let served = host.remote_refs().unwrap();
1510
    let acc = served
1511
        .refs
1512
        .iter()
1513
        .find(|r| r.name == "main")
1514
        .unwrap()
1515
        .accepted
1516
        .clone()
1517
        .expect("served with the refs");
1518
    let signer = sa.sigs[0].key;
1519
    assert_eq!(
1520
        a.certified_time(&signer, &sa, Some(&acc)),
1521
        acc.attest.hlc.wall_ms
1522
    );
1523
    assert_eq!(a.certified_time(&signer, &sa, None), sa.attest.hlc.wall_ms);
1524
    let stranger_sk = SecretKey::generate();
1525
    let stranger = stranger_sk.identity("stranger", "s@x", 1);
1526
    let mut forged = acc.clone();
1527
    forged.sigs = vec![stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.attest.hash())];
1528
    assert_eq!(
1529
        a.certified_time(&signer, &sa, Some(&forged)),
1530
        sa.attest.hlc.wall_ms,
1531
        "not the issuer's"
1532
    );
1533
    let mut elsewhere = acc.clone();
1534
    elsewhere.attest.body = AttestBody::Accepted {
1535
        attest: ObjectRef([7; 32]),
1536
    };
1537
    elsewhere.sigs = vec![hub_sk.sign(Domain::Attest, &hub.hash(), &elsewhere.attest.hash())];
1538
    assert_eq!(
1539
        a.certified_time(&signer, &sa, Some(&elsewhere)),
1540
        sa.attest.hlc.wall_ms,
1541
        "another attestation's"
1542
    );
1543
    a.pull("origin").unwrap();
1544
    // gc keeps the acceptance with the attestation.
1545
    host.gc(true).unwrap();
1546
    assert!(host.acceptance_of(&attest_ref).unwrap().is_some());
1547
1548
    let late = agent("late", "agent:claude@ada", now - 1_200_000, now - 600_000);
1549
    let r = late.push("origin", false).unwrap();
1550
    assert!(
1551
        !r[0].ok && r[0].reason.contains("may not update"),
1552
        "an expired certificate: {r:?}"
1553
    );
1554
    let other = agent("other", "agent:mallory@ada", now - 60_000, now + 600_000);
1555
    let r = other.push("origin", false).unwrap();
1556
    assert!(
1557
        !r[0].ok && r[0].reason.contains("may not update"),
1558
        "a subject not granted: {r:?}"
1559
    );
1560
}
1561
1562
/// A tag made under one short-lived key and pushed under another: its
1563
/// signer travels with the push (identity and certificate), so a receiver
1564
/// that has never seen that key accepts it. A tag-only push by a keyless
1565
/// agent was refused "unknown key" (found releasing OxygenFlow 0.2.0).
1566
#[test]
1567
fn a_tag_signed_by_an_earlier_short_lived_key_is_pushed() {
1568
    use crate::cert::{Certificate, SignedCertificate};
1569
    use crate::identity::Scope;
1570
    hermetic();
1571
    let dir = tempfile::tempdir().unwrap();
1572
    let root = dir.path();
1573
    let _origin = Repo::init(&root.join("origin")).unwrap();
1574
    let url = root.join("origin").to_string_lossy().to_string();
1575
    let mut a = Repo::clone(&url, &root.join("a"))
1576
        .unwrap()
1577
        .with_home(root.join("home-a"));
1578
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1579
        .unwrap();
1580
    write(&root.join("a"), "a.txt", b"a\n");
1581
    a.commit("a", &[]).unwrap();
1582
    a.policy_init().unwrap();
1583
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1584
    let hub_sk = SecretKey::generate();
1585
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1586
    a.policy_grant_subject(
1587
        "agent:claude@ada",
1588
        hub.clone(),
1589
        Scope::CHANGES | Scope::REFS,
1590
        Some("*"),
1591
    )
1592
    .unwrap();
1593
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1594
1595
    let now = Hlc::now().wall_ms;
1596
    let mut agent = Repo::clone(&url, &root.join("agent"))
1597
        .unwrap()
1598
        .with_home(root.join("home-agent"));
1599
    agent.store().put_identity(&hub).unwrap();
1600
    let certify = |agent: &Repo, id| {
1601
        let cert = SignedCertificate::sign(
1602
            Certificate {
1603
                key: id,
1604
                issuer: hub.hash(),
1605
                subject: "agent:claude@ada".into(),
1606
                claims: vec![],
1607
                scope: Scope::CHANGES | Scope::REFS,
1608
                not_before: now - 60_000,
1609
                expires: now + 600_000,
1610
                grant: None,
1611
            },
1612
            &hub,
1613
            &hub_sk,
1614
        );
1615
        agent.store().put_certificate(&cert).unwrap();
1616
    };
1617
    // The tag, under the first short-lived key.
1618
    let (first, first_id) = agent
1619
        .create_identity("claude", "[email protected]", IdentityScope::User)
1620
        .unwrap();
1621
    certify(&agent, first_id);
1622
    let heads = agent.bookmark_heads().unwrap();
1623
    agent.tag_create("v1", &heads, "first").unwrap();
1624
    // The push, under a second one (a later process's ten-minute key).
1625
    let (second, second_id) = agent
1626
        .create_identity("claude", "[email protected]", IdentityScope::User)
1627
        .unwrap();
1628
    assert_ne!(first, second);
1629
    certify(&agent, second_id);
1630
    agent
1631
        .set_user_config("author.signer", &second.to_hex())
1632
        .unwrap();
1633
    let host = Repo::open(&root.join("origin")).unwrap();
1634
    assert!(
1635
        host.store().get_identity(&first).is_err(),
1636
        "the host has never seen the tag's key"
1637
    );
1638
    let r = agent.push("origin", false).unwrap();
1639
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1640
    let host = Repo::open(&root.join("origin")).unwrap();
1641
    assert!(
1642
        host.tag_refs().unwrap().iter().any(|t| t.name == "v1"),
1643
        "the tag arrived"
1644
    );
1645
}
1646
1647
/// oxygen#129: a short-lived key's tag is checked on a fetch at a time its
1648
/// signer did not choose, its issuer's acceptance, never at the time it
1649
/// claims nor at the fetch's (when the ten-minute certificate has long
1650
/// expired). Without an acceptance it is left out and said so; with one
1651
/// inside the certificate's window it is fetched however much later, and
1652
/// a host it is pushed on to keeps and serves the acceptance.
1653
#[test]
1654
fn a_short_lived_key_s_tag_is_fetched_at_its_issuer_s_acceptance() {
1655
    use crate::cert::{Certificate, SignedCertificate};
1656
    use crate::identity::Scope;
1657
    hermetic();
1658
    let dir = tempfile::tempdir().unwrap();
1659
    let root = dir.path();
1660
    let _origin = Repo::init(&root.join("origin")).unwrap();
1661
    let url = root.join("origin").to_string_lossy().to_string();
1662
    let mut a = Repo::clone(&url, &root.join("a"))
1663
        .unwrap()
1664
        .with_home(root.join("home-a"));
1665
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1666
        .unwrap();
1667
    write(&root.join("a"), "a.txt", b"a\n");
1668
    a.commit("a", &[]).unwrap();
1669
    a.policy_init().unwrap();
1670
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1671
    let hub_sk = SecretKey::generate();
1672
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1673
    a.policy_grant_subject(
1674
        "agent:claude@ada",
1675
        hub.clone(),
1676
        Scope::CHANGES | Scope::REFS,
1677
        Some("*"),
1678
    )
1679
    .unwrap();
1680
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1681
1682
    let now = Hlc::now().wall_ms;
1683
    // An agent whose key the hub certified from `from` to `to`.
1684
    let agent = |name: &str, from: u64, to: u64| {
1685
        let mut r = Repo::clone(&url, &root.join(name))
1686
            .unwrap()
1687
            .with_home(root.join(format!("home-{name}")));
1688
        r.store().put_identity(&hub).unwrap();
1689
        let (_, id) = r
1690
            .create_identity(name, "[email protected]", IdentityScope::User)
1691
            .unwrap();
1692
        let cert = SignedCertificate::sign(
1693
            Certificate {
1694
                key: id,
1695
                issuer: hub.hash(),
1696
                subject: "agent:claude@ada".into(),
1697
                claims: vec![],
1698
                scope: Scope::CHANGES | Scope::REFS,
1699
                not_before: from,
1700
                expires: to,
1701
                grant: None,
1702
            },
1703
            &hub,
1704
            &hub_sk,
1705
        );
1706
        r.store().put_certificate(&cert).unwrap();
1707
        r
1708
    };
1709
1710
    // A tag by a key certified now, pushed to a host that records no
1711
    // acceptance (a path on disk): it lands, but a fetch has no time to
1712
    // check its certificate at, so it is left out and the fetch goes on.
1713
    let claude = agent("claude", now - 60_000, now + 600_000);
1714
    let heads = claude.bookmark_heads().unwrap();
1715
    claude.tag_create("v1", &heads, "one").unwrap();
1716
    let r = claude.push("origin", false).unwrap();
1717
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1718
    let b = Repo::clone(&url, &root.join("b"))
1719
        .unwrap()
1720
        .with_home(root.join("home-b"));
1721
    let rep = b.fetch("origin").unwrap();
1722
    assert!(
1723
        rep.skipped
1724
            .iter()
1725
            .any(|(n, why)| n == "tags/v1" && why.contains("no time to check its certificate at")),
1726
        "{rep:?}"
1727
    );
1728
    assert_eq!(b.tag_heads("v1").unwrap(), None);
1729
1730
    // The host's acceptance, signed by the certificate's issuer, served
1731
    // with the tag: fetched.
1732
    let host = Repo::open(&root.join("origin"))
1733
        .unwrap()
1734
        .with_acceptor(hub.clone(), hub_sk.clone());
1735
    let (v1, _) = host.tag_attest("v1").unwrap().unwrap();
1736
    host.record_acceptance(&v1).unwrap();
1737
    let served = host.tag_refs().unwrap();
1738
    assert!(served
1739
        .iter()
1740
        .any(|t| t.name == "v1" && t.accepted.is_some()));
1741
    let rep = b.fetch("origin").unwrap();
1742
    assert!(rep.skipped.is_empty(), "{rep:?}");
1743
    assert_eq!(b.tag_heads("v1").unwrap(), Some(heads.clone()));
1744
    // gc keeps the acceptance with the tag.
1745
    host.gc(true).unwrap();
1746
    assert!(host.acceptance_of(&v1).unwrap().is_some());
1747
1748
    // Long after: a key whose certificate expired an hour ago may not
1749
    // create a tag now.
1750
    let late = agent("late", now - 7_200_000, now - 3_600_000);
1751
    late.tag_create("v2", &heads, "two").unwrap();
1752
    let r = late.push("origin", false).unwrap();
1753
    assert!(
1754
        r.iter()
1755
            .any(|x| x.name == "tags/v2" && !x.ok && x.reason.contains("may not create")),
1756
        "{r:?}"
1757
    );
1758
    // With its issuer's acceptance from inside the window (as a hub gave
1759
    // it then, passed on to another host), it is taken at that time: by
1760
    // the host it is pushed to, which keeps it, and by a fresh clone.
1761
    let (v2, _) = late.tag_attest("v2").unwrap().unwrap();
1762
    let acc = Attest {
1763
        repo: late.id().unwrap(),
1764
        hlc: Hlc {
1765
            wall_ms: now - 5_400_000,
1766
            logical: 0,
1767
        },
1768
        body: AttestBody::Accepted { attest: v2 },
1769
    };
1770
    let sig = hub_sk.sign(Domain::Attest, &hub.hash(), &acc.hash());
1771
    // One by any other key gives no time.
1772
    let stranger_sk = SecretKey::generate();
1773
    let stranger = stranger_sk.identity("stranger", "[email protected]", 1);
1774
    let forged = stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.hash());
1775
    late.keep_acceptance(
1776
        &v2,
1777
        &SignedAttest {
1778
            attest: acc.clone(),
1779
            sigs: vec![forged],
1780
        },
1781
    )
1782
    .unwrap();
1783
    let r = late.push("origin", false).unwrap();
1784
    assert!(
1785
        r.iter().any(|x| x.name == "tags/v2" && !x.ok),
1786
        "not the issuer's: {r:?}"
1787
    );
1788
    let theirs = SignedAttest {
1789
        attest: acc,
1790
        sigs: vec![sig],
1791
    };
1792
    // Kept beside the stranger's: the issuer's is the one sent.
1793
    late.keep_acceptance(&v2, &theirs).unwrap();
1794
    let r = late.push("origin", false).unwrap();
1795
    // (Its re-attestation of main is refused: an expired key moves no
1796
    // bookmark.)
1797
    assert!(r.iter().any(|x| x.name == "tags/v2" && x.ok), "{r:?}");
1798
    let host = Repo::open(&root.join("origin")).unwrap();
1799
    let (hv2, _) = host.tag_attest("v2").unwrap().unwrap();
1800
    assert_eq!(hv2, v2);
1801
    assert!(host
1802
        .store()
1803
        .index_get_pub("accepted", &v2)
1804
        .unwrap()
1805
        .contains(&theirs.attest.hash()));
1806
    let c = Repo::clone(&url, &root.join("c"))
1807
        .unwrap()
1808
        .with_home(root.join("home-c"));
1809
    assert_eq!(c.tag_heads("v2").unwrap(), Some(heads.clone()));
1810
    assert_eq!(c.tag_heads("v1").unwrap(), Some(heads));
1811
}
1812
1813
/// oxygenhub#266: a short-lived key its issuer certified moves a bookmark
1814
/// and signs no change (a keyless agent naming a bookmark). A third
1815
/// party's clone gets the key's identity, its certificate and the
1816
/// issuer's identity with the fetch, so the policy's subject grant
1817
/// authorizes the move and the signature verifies.
1818
#[test]
1819
fn a_bookmark_moved_by_a_certified_key_alone_is_fetched() {
1820
    use crate::cert::{Certificate, SignedCertificate};
1821
    use crate::identity::Scope;
1822
    hermetic();
1823
    let dir = tempfile::tempdir().unwrap();
1824
    let root = dir.path();
1825
    let _origin = Repo::init(&root.join("origin")).unwrap();
1826
    let url = root.join("origin").to_string_lossy().to_string();
1827
    let mut a = Repo::clone(&url, &root.join("a"))
1828
        .unwrap()
1829
        .with_home(root.join("home-a"));
1830
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1831
        .unwrap();
1832
    write(&root.join("a"), "a.txt", b"a\n");
1833
    a.commit("a", &[]).unwrap();
1834
    a.policy_init().unwrap();
1835
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1836
    let hub_sk = SecretKey::generate();
1837
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1838
    a.policy_grant_subject(
1839
        "agent:claude@ada",
1840
        hub.clone(),
1841
        Scope::CHANGES | Scope::REFS,
1842
        None,
1843
    )
1844
    .unwrap();
1845
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1846
1847
    let now = Hlc::now().wall_ms;
1848
    let mut agent = Repo::clone(&url, &root.join("agent"))
1849
        .unwrap()
1850
        .with_home(root.join("home-agent"));
1851
    let (key, id) = agent
1852
        .create_identity("claude", "[email protected]", IdentityScope::User)
1853
        .unwrap();
1854
    let cert = SignedCertificate::sign(
1855
        Certificate {
1856
            key: id,
1857
            issuer: hub.hash(),
1858
            subject: "agent:claude@ada".into(),
1859
            claims: vec![],
1860
            scope: Scope::CHANGES | Scope::REFS,
1861
            not_before: now - 60_000,
1862
            expires: now + 600_000,
1863
            grant: None,
1864
        },
1865
        &hub,
1866
        &hub_sk,
1867
    );
1868
    agent.store().put_identity(&hub).unwrap();
1869
    agent.store().put_certificate(&cert).unwrap();
1870
    let heads = agent.bookmark_heads().unwrap();
1871
    agent.bookmark_create("agent-work", Some(&heads)).unwrap();
1872
    let r = agent.push_bookmark("origin", "agent-work", false).unwrap();
1873
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1874
    let host = Repo::open(&root.join("origin")).unwrap();
1875
    let (_, sa) = host.latest_ref_attest("agent-work").unwrap().unwrap();
1876
    assert_eq!(sa.sigs[0].key, key, "the certified key alone moved it");
1877
1878
    // A fetch naming no change brings the certificate and both identities.
1879
    let bundle = host.bundle_raw_for(&[], None).unwrap();
1880
    assert!(bundle.changes.is_empty() && bundle.raw_changes.is_empty());
1881
    assert_eq!(bundle.certificates.len(), 1);
1882
    for k in [key, hub.hash()] {
1883
        assert!(bundle
1884
            .objects
1885
            .iter()
1886
            .any(|(t, b)| *t == ObjectType::Identity && hash_object(*t, b) == k));
1887
    }
1888
1889
    let c = Repo::clone(&url, &root.join("c")).unwrap();
1890
    let tracked = c.view().unwrap().remotes["origin"].clone();
1891
    assert_eq!(
1892
        tracked.get("agent-work"),
1893
        host.view().unwrap().bookmarks.get("agent-work")
1894
    );
1895
    assert!(c.store().certificate_of(&key).unwrap().is_some());
1896
}
1897
1898
/// Trusted time (oxygenhub#240, spec §14.8): a fetched attestation by a
1899
/// short-lived key is judged at its integrated time, the earliest time a
1900
/// pinned witness cosigned a checkpoint holding it. A certificate valid
1901
/// then but expired now passes; a witness this user does not trust gives
1902
/// no time (the earlier rule, said so); a backdated attestation is noted;
1903
/// an answer without the new fields is judged as before.
1904
#[test]
1905
fn a_fetched_attestation_is_judged_at_its_integrated_time() {
1906
    use super::transparency::LogCheck;
1907
    use crate::cert::{Certificate, SignedCertificate};
1908
    use crate::identity::Scope;
1909
    use crate::protocol::{Integration, Logged, RefsResponse, RemoteRef};
1910
    use crate::tlog::{self, Checkpoint, Entry, Hash, Integrated, Note};
1911
    hermetic();
1912
    let dir = tempfile::tempdir().unwrap();
1913
    let root = dir.path();
1914
    let mut a = Repo::init(&root.join("a"))
1915
        .unwrap()
1916
        .with_home(root.join("home-a"));
1917
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1918
        .unwrap();
1919
    write(&root.join("a"), "a.txt", b"a\n");
1920
    a.commit("a", &[]).unwrap();
1921
    a.policy_init().unwrap();
1922
    let issuer_sk = SecretKey::generate();
1923
    let issuer = issuer_sk.identity("hub", "[email protected]", 1);
1924
    a.policy_grant_subject(
1925
        "agent:claude@ada",
1926
        issuer.clone(),
1927
        Scope::CHANGES | Scope::REFS,
1928
        None,
1929
    )
1930
    .unwrap();
1931
    let p = a.current_policy().unwrap().unwrap().1.policy;
1932
1933
    // An agent key the issuer certified for ten minutes two hours ago.
1934
    let now = Hlc::now().wall_ms;
1935
    let t0 = now - 2 * 3_600_000;
1936
    let agent_sk = SecretKey::generate();
1937
    let agent = agent_sk.identity("claude", "[email protected]", t0);
1938
    let cert = SignedCertificate::sign(
1939
        Certificate {
1940
            key: agent.clone(),
1941
            issuer: issuer.hash(),
1942
            subject: "agent:claude@ada".into(),
1943
            claims: vec![],
1944
            scope: Scope::CHANGES | Scope::REFS,
1945
            not_before: t0,
1946
            expires: t0 + 600_000,
1947
            grant: None,
1948
        },
1949
        &issuer,
1950
        &issuer_sk,
1951
    );
1952
    a.store().put_identity(&agent).unwrap();
1953
    a.store().put_certificate(&cert).unwrap();
1954
    let signer = agent.hash();
1955
    let attested = |claimed: u64| {
1956
        let attest = Attest {
1957
            repo: a.id().unwrap(),
1958
            hlc: Hlc {
1959
                wall_ms: claimed,
1960
                logical: 0,
1961
            },
1962
            body: AttestBody::Ref {
1963
                name: "main".into(),
1964
                old_state: ObjectRef([1; 32]),
1965
                new_state: ObjectRef([2; 32]),
1966
                serial: 1,
1967
            },
1968
        };
1969
        let sig = agent_sk.sign(Domain::Attest, &signer, &attest.hash());
1970
        SignedAttest {
1971
            attest,
1972
            sigs: vec![sig],
1973
        }
1974
    };
1975
1976
    // The hub's log: eight entries, the attestation's at 3, the latest
1977
    // checkpoint of 8, and one of 4 that witnesses cosigned.
1978
    let log_sk = SecretKey::generate();
1979
    let log_key = log_sk.identity("hub.example", "[email protected]", 1);
1980
    let origin = "hub.example/log";
1981
    let hub = "https://hub.example";
1982
    let url = "https://hub.example/ada/a";
1983
    let w_sk = SecretKey::generate();
1984
    let w = w_sk.identity("w", "[email protected]", 1);
1985
    let stranger_sk = SecretKey::generate();
1986
    let stranger = stranger_sk.identity("s", "[email protected]", 1);
1987
    let sa = attested(t0 + 300_000);
1988
    let entry_of = |i: u64| {
1989
        let (kind, object) = if i == 3 {
1990
            ("ref", sa.attest.hash())
1991
        } else {
1992
            ("seal", ObjectRef([i as u8; 32]))
1993
        };
1994
        Entry {
1995
            kind: kind.into(),
1996
            repo: sa.attest.repo,
1997
            object,
1998
            signers: vec![signer],
1999
            received: t0 + 300_000,
2000
        }
2001
        .encode()
2002
    };
2003
    let mut stored: Vec<Hash> = Vec::new();
2004
    for i in 0..8 {
2005
        let add = tlog::stored_hashes_for_leaf(i, tlog::leaf_hash(&entry_of(i)), &stored).unwrap();
2006
        stored.extend(add);
2007
    }
2008
    let note_of = |n: u64, cosigners: &[(&str, &Identity, &SecretKey, u64)]| {
2009
        let mut note = Checkpoint {
2010
            origin: origin.into(),
2011
            size: n,
2012
            root: tlog::tree_hash(n, &stored).unwrap(),
2013
            extensions: vec![],
2014
        }
2015
        .sign(&log_key, &log_sk)
2016
        .unwrap();
2017
        for (name, id, sk, t) in cosigners {
2018
            note.sigs
2019
                .extend(tlog::cosign(&note.text, name, id, sk, *t).unwrap());
2020
        }
2021
        note.encode()
2022
    };
2023
    let latest = note_of(8, &[]);
2024
    let witnessed_at = (t0 + 360_000) / 1000;
2025
    let cosigned = note_of(
2026
        4,
2027
        &[
2028
            ("w.example", &w, &w_sk, witnessed_at),
2029
            ("s.example", &stranger, &stranger_sk, 1),
2030
        ],
2031
    );
2032
    let answer = |integration: Vec<Integration>, witnesses: Vec<(String, Vec<u8>)>| RefsResponse {
2033
        refs: vec![RemoteRef {
2034
            name: "main".into(),
2035
            state: ObjectRef([2; 32]),
2036
            heads: vec![],
2037
            attestation: Some(sa.clone()),
2038
            last_serial: None,
2039
            accepted: None,
2040
            logged: Some(Logged {
2041
                index: 3,
2042
                entry: entry_of(3),
2043
                proof: tlog::prove_inclusion(8, 3, &stored).unwrap(),
2044
            }),
2045
            integration,
2046
        }],
2047
        log: Some(latest.clone()),
2048
        witnesses,
2049
        ..RefsResponse::default()
2050
    };
2051
    let proof4 = tlog::prove_inclusion(4, 3, &stored).unwrap();
2052
    let served = vec![Integration {
2053
        note: cosigned.clone(),
2054
        proof: proof4.clone(),
2055
    }];
2056
    let listed = vec![("w.example".to_string(), w.encode())];
2057
    // This user saw the hub's log before (pinned, so nothing is fetched).
2058
    a.remember_log(hub, &log_key, &Note::parse(&latest).unwrap())
2059
        .unwrap();
2060
2061
    // The witness is pinned on first sight, silently; the stranger's
2062
    // earlier cosignature counts for nothing.
2063
    let resp = answer(served.clone(), listed.clone());
2064
    let lc = a.check_log(url, None, &resp).unwrap();
2065
    assert!(lc.notes.is_empty(), "{:?}", lc.notes);
2066
    let t = lc.time_of("main").unwrap();
2067
    assert_eq!((t.time, t.witness.as_str()), (witnessed_at, "w.example"));
2068
    // The certificate expired an hour and fifty minutes ago, but covered
2069
    // the integrated time: accepted, and nothing to say.
2070
    assert!(cert.cert.expires < now);
2071
    let mut notes = Vec::new();
2072
    a.authorize_in_time(&p, "origin", &resp.refs[0], &sa, &signer, &lc, &mut notes)
2073
        .unwrap();
2074
    assert!(notes.is_empty(), "{notes:?}");
2075
2076
    // Only the stranger cosigned: no witnessed time, so the earlier rule
2077
    // (the attestation's own time, inside the window), said so.
2078
    let lonely = vec![Integration {
2079
        note: note_of(4, &[("s.example", &stranger, &stranger_sk, 1)]),
2080
        proof: proof4.clone(),
2081
    }];
2082
    let resp = answer(lonely, vec![]);
2083
    let lc = a.check_log(url, None, &resp).unwrap();
2084
    assert!(lc
2085
        .time_of("main")
2086
        .unwrap_err()
2087
        .contains("no witness this user trusts"));
2088
    let mut notes = Vec::new();
2089
    a.authorize_in_time(&p, "origin", &resp.refs[0], &sa, &signer, &lc, &mut notes)
2090
        .unwrap();
2091
    assert!(
2092
        notes.len() == 1 && notes[0].contains("not at a witnessed time"),
2093
        "{notes:?}"
2094
    );
2095
2096
    // A witness listed later under the pinned name with another key is
2097
    // pinned with a note, as a new log key is.
2098
    let resp = answer(
2099
        served.clone(),
2100
        vec![("w.example".into(), stranger.encode())],
2101
    );
2102
    let lc = a.check_log(url, None, &resp).unwrap();
2103
    assert!(
2104
        lc.notes.iter().any(|n| n.contains("another key")),
2105
        "{:?}",
2106
        lc.notes
2107
    );
2108
    assert!(
2109
        lc.time_of("main").is_err(),
2110
        "w's cosignature is by its old key"
2111
    );
2112
    a.check_log(url, None, &answer(served.clone(), listed.clone()))
2113
        .unwrap();
2114
2115
    // An old peer's answer: no log, no witnesses, no integration. Judged
2116
    // as before, silently.
2117
    let mut old = answer(vec![], vec![]);
2118
    old.log = None;
2119
    old.refs[0].logged = None;
2120
    let lc = a.check_log(url, None, &old).unwrap();
2121
    assert!(!lc.kept && lc.notes.is_empty());
2122
    let mut notes = Vec::new();
2123
    a.authorize_in_time(&p, "origin", &old.refs[0], &sa, &signer, &lc, &mut notes)
2124
        .unwrap();
2125
    assert!(notes.is_empty(), "{notes:?}");
2126
2127
    // Judged at given integrated times.
2128
    let at = |secs_after_t0: u64| {
2129
        let mut times = std::collections::HashMap::new();
2130
        times.insert(
2131
            "main".to_string(),
2132
            Ok(Integrated {
2133
                time: (t0 + secs_after_t0 * 1000) / 1000,
2134
                witness: "w.example".into(),
2135
                size: 4,
2136
            }),
2137
        );
2138
        LogCheck {
2139
            kept: true,
2140
            times,
2141
            ..LogCheck::default()
2142
        }
2143
    };
2144
    let judged = |sa: &SignedAttest, lc: &LogCheck| {
2145
        let mut notes = Vec::new();
2146
        a.authorize_in_time(&p, "origin", &old.refs[0], sa, &signer, lc, &mut notes)
2147
            .map(|_| notes)
2148
    };
2149
    // Claimed inside the window, first witnessed an hour later, after
2150
    // the certificate expired: backdated, or held back. Accepted by the
2151
    // earlier rule while logs are new, with both said.
2152
    let notes = judged(&sa, &at(3600)).unwrap();
2153
    assert!(
2154
        notes
2155
            .iter()
2156
            .any(|n| n.contains("had lapsed when witness w.example"))
2157
            && notes
2158
                .iter()
2159
                .any(|n| n.contains("55 minutes before witness")),
2160
        "{notes:?}"
2161
    );
2162
    // Claimed after the certificate expired, but witnessed inside its
2163
    // window: the clock the signer did not choose decides. The gap is
2164
    // still noted.
2165
    let fast = attested(now);
2166
    let notes = judged(&fast, &at(400)).unwrap();
2167
    assert!(
2168
        notes.len() == 1 && notes[0].contains("after witness w.example saw it"),
2169
        "{notes:?}"
2170
    );
2171
    // Claimed and witnessed after it expired: refused, as before.
2172
    assert!(judged(&fast, &at(3600)).is_err());
2173
    // A gap within ten minutes is nothing to note.
2174
    assert!(judged(&sa, &at(500)).unwrap().is_empty());
2175
}
2176
2177
/// Keyless step 5 (oxygenhub#241): an agent's fresh key, certified for a
2178
/// subject the author granted, seals changes in the author's name; with
2179
/// no grant, a stranger's, or one that had ended, it is neither the
2180
/// author nor a delegate.
2181
/// oxygen#135: an owner renews or rotates with every delegation, and a
2182
/// repository may name the newest key as the author; the agent's grant by
2183
/// the earlier key still counts, but not one that key made after.
2184
#[test]
2185
fn a_grant_outlives_its_owner_s_rotation() {
2186
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
2187
    use crate::identity::Scope;
2188
    hermetic();
2189
    let dir = tempfile::tempdir().unwrap();
2190
    let root = dir.path();
2191
    let mut a = Repo::init(&root.join("a"))
2192
        .unwrap()
2193
        .with_home(root.join("home-a"));
2194
    let (old, _) = a
2195
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2196
        .unwrap();
2197
    let (_, old_sk) = a.secret_key().unwrap().unwrap();
2198
    let old_id = a.identity(&old).unwrap();
2199
    let hub_sk = SecretKey::generate();
2200
    let hub = hub_sk.identity("hub", "[email protected]", 1);
2201
    let now = Hlc::now().wall_ms;
2202
    let grant = |from: u64| {
2203
        SignedGrant::sign(
2204
            Grant {
2205
                grantor: old,
2206
                subject: "agent:claude@ada".into(),
2207
                issuer: hub.hash(),
2208
                scope: Scope::CHANGES | Scope::SEAL,
2209
                not_before: from,
2210
                expires: now + 86_400_000,
2211
            },
2212
            &old_id,
2213
            &old_sk,
2214
        )
2215
    };
2216
    let before = grant(now - 60_000);
2217
    let after = grant(now + 60_000);
2218
    let rot = a.renew_identity(None).unwrap();
2219
    assert_ne!(rot.new, old);
2220
    let agent = |name: &str, g: SignedGrant| {
2221
        let mut r = Repo::init(&root.join(name))
2222
            .unwrap()
2223
            .with_home(root.join(format!("home-{name}")));
2224
        let (key, id) = r
2225
            .create_identity(name, "[email protected]", IdentityScope::User)
2226
            .unwrap();
2227
        for i in [&old_id, &rot.identity, &hub] {
2228
            r.store().put_identity(i).unwrap();
2229
        }
2230
        r.set_user_config("author.key", &rot.new.to_hex()).unwrap();
2231
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
2232
        let cert = SignedCertificate::sign(
2233
            Certificate {
2234
                key: id,
2235
                issuer: hub.hash(),
2236
                subject: "agent:claude@ada".into(),
2237
                claims: vec![],
2238
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
2239
                not_before: now - 60_000,
2240
                expires: now + 600_000,
2241
                grant: Some(g),
2242
            },
2243
            &hub,
2244
            &hub_sk,
2245
        );
2246
        r.store().put_certificate(&cert).unwrap();
2247
        write(&root.join(name), "work.txt", b"agent work\n");
2248
        let h = r.commit("work", &[]).unwrap();
2249
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, rot.new);
2250
        r.seal(&[h]).unwrap();
2251
        (r, h)
2252
    };
2253
    let (r, h) = agent("kept", before);
2254
    assert!(
2255
        matches!(
2256
            r.authenticate_change(&h).unwrap(),
2257
            SignatureStatus::Valid { .. }
2258
        ),
2259
        "{:?}",
2260
        r.authenticate_change(&h).unwrap()
2261
    );
2262
    let (r, h) = agent("late", after);
2263
    assert!(
2264
        matches!(r.authenticate_change(&h).unwrap(), SignatureStatus::Invalid(e) if e.contains("neither")),
2265
        "a grant the old key made after the rotation: {:?}",
2266
        r.authenticate_change(&h).unwrap()
2267
    );
2268
}
2269
2270
#[test]
2271
fn a_certified_key_acts_for_its_author_under_a_grant() {
2272
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
2273
    use crate::identity::{Identity, Scope};
2274
    hermetic();
2275
    let dir = tempfile::tempdir().unwrap();
2276
    let root = dir.path();
2277
    let _origin = Repo::init(&root.join("origin")).unwrap();
2278
    let url = root.join("origin").to_string_lossy().to_string();
2279
    let mut a = Repo::clone(&url, &root.join("a"))
2280
        .unwrap()
2281
        .with_home(root.join("home-a"));
2282
    let (ada, _) = a
2283
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2284
        .unwrap();
2285
    write(&root.join("a"), "a.txt", b"a\n");
2286
    a.commit("a", &[]).unwrap();
2287
    a.policy_init().unwrap();
2288
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2289
    let hub_sk = SecretKey::generate();
2290
    let hub = hub_sk.identity("hub", "[email protected]", 1);
2291
    a.policy_grant_subject(
2292
        "agent:claude@ada",
2293
        hub.clone(),
2294
        Scope::CHANGES | Scope::REFS,
2295
        None,
2296
    )
2297
    .unwrap();
2298
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2299
    let (_, ada_sk) = a.secret_key().unwrap().unwrap();
2300
    let ada_id = a.identity(&ada).unwrap();
2301
2302
    let now = Hlc::now().wall_ms;
2303
    let grant = |by: &Identity, sk: &SecretKey, from: u64, to: u64| {
2304
        SignedGrant::sign(
2305
            Grant {
2306
                grantor: by.hash(),
2307
                subject: "agent:claude@ada".into(),
2308
                issuer: hub.hash(),
2309
                scope: Scope::CHANGES | Scope::SEAL,
2310
                not_before: from,
2311
                expires: to,
2312
            },
2313
            by,
2314
            sk,
2315
        )
2316
    };
2317
    // Ada's work as an agent runs it: Ada the author, a fresh key the hub
2318
    // certified (with `g` inside) the signer.
2319
    let agent = |name: &str, g: Option<SignedGrant>| {
2320
        let mut r = Repo::clone(&url, &root.join(name))
2321
            .unwrap()
2322
            .with_home(root.join(format!("home-{name}")));
2323
        let (key, id) = r
2324
            .create_identity(name, "[email protected]", IdentityScope::User)
2325
            .unwrap();
2326
        r.set_user_config("author.key", &ada.to_hex()).unwrap();
2327
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
2328
        let cert = SignedCertificate::sign(
2329
            Certificate {
2330
                key: id,
2331
                issuer: hub.hash(),
2332
                subject: "agent:claude@ada".into(),
2333
                claims: vec![],
2334
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
2335
                not_before: now - 60_000,
2336
                expires: now + 600_000,
2337
                grant: g,
2338
            },
2339
            &hub,
2340
            &hub_sk,
2341
        );
2342
        r.store().put_identity(&hub).unwrap();
2343
        r.store().put_certificate(&cert).unwrap();
2344
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
2345
        let h = r.commit("work", &[]).unwrap();
2346
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, ada);
2347
        (r, key, h)
2348
    };
2349
2350
    let (claude, key, h) = agent(
2351
        "claude",
2352
        Some(grant(&ada_id, &ada_sk, now - 60_000, now + 86_400_000)),
2353
    );
2354
    let r = claude.push("origin", false).unwrap();
2355
    assert!(r.iter().all(|x| x.ok), "{r:?}");
2356
    let host = Repo::open(&root.join("origin")).unwrap();
2357
    assert!(
2358
        matches!(
2359
            host.authenticate_change(&h).unwrap(),
2360
            SignatureStatus::Valid { key: k, sealed: true, name, .. } if k == key && name == "agent:claude@ada"
2361
        ),
2362
        "named by its certificate's subject"
2363
    );
2364
    a.pull("origin").unwrap();
2365
    assert!(matches!(
2366
        a.authenticate_change(&h).unwrap(),
2367
        SignatureStatus::Valid { key: k, .. } if k == key
2368
    ));
2369
2370
    let (none, _, _) = agent("none", None);
2371
    let r = none.push("origin", false).unwrap();
2372
    assert!(r.iter().all(|x| !x.ok), "no grant: {r:?}");
2373
    let mallory_sk = SecretKey::generate();
2374
    let mallory = mallory_sk.identity("Mallory", "[email protected]", 1);
2375
    let (stranger, _, _) = agent(
2376
        "stranger",
2377
        Some(grant(&mallory, &mallory_sk, now - 60_000, now + 600_000)),
2378
    );
2379
    let r = stranger.push("origin", false).unwrap();
2380
    assert!(r.iter().all(|x| !x.ok), "a stranger's grant: {r:?}");
2381
    let (ended, _, eh) = agent(
2382
        "ended",
2383
        Some(grant(&ada_id, &ada_sk, now - 7_200_000, now - 3_600_000)),
2384
    );
2385
    let r = ended.push("origin", false).unwrap();
2386
    assert!(r.iter().all(|x| !x.ok), "an ended grant: {r:?}");
2387
    assert!(matches!(
2388
        ended.authenticate_change(&eh).unwrap(),
2389
        SignatureStatus::Invalid(e) if e.contains("grant did not cover")
2390
    ));
2391
}
2392
2393
#[test]
2394
fn trust_policy_governs_pushes_and_fetches() {
2395
    hermetic();
2396
    let dir = tempfile::tempdir().unwrap();
2397
    let root = dir.path();
2398
    let origin = Repo::init(&root.join("origin")).unwrap();
2399
    let url = root.join("origin").to_string_lossy().to_string();
2400
2401
    // A is the root. Before the policy, an unsigned push from B is fine.
2402
    let mut a = Repo::clone(&url, &root.join("a"))
2403
        .unwrap()
2404
        .with_home(root.join("home-a"));
2405
    let (key_a, _) = a
2406
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2407
        .unwrap();
2408
    let mut b = Repo::clone(&url, &root.join("b"))
2409
        .unwrap()
2410
        .with_home(root.join("home-b"));
2411
    write(&root.join("b"), "b.txt", b"b\n");
2412
    b.commit("unsigned before policy", &[]).unwrap();
2413
    assert!(b.push("origin", false).unwrap()[0].ok);
2414
    origin.refresh().unwrap();
2415
2416
    // A creates the policy and pushes it; origin now enforces it.
2417
    write(&root.join("a"), "a.txt", b"a\n");
2418
    a.commit("a", &[]).unwrap();
2419
    let sp = a.policy_init().unwrap();
2420
    assert_eq!(sp.policy.serial, 1);
2421
    a.pull("origin").unwrap();
2422
    let results = a.push("origin", false).unwrap();
2423
    origin.refresh().unwrap();
2424
    assert!(results.iter().all(|r| r.ok), "{results:?}");
2425
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
2426
2427
    // B pulls the policy. Without an identity B cannot push at all.
2428
    b.pull("origin").unwrap();
2429
    assert!(
2430
        b.current_policy().unwrap().is_some(),
2431
        "the policy arrived with the fetch"
2432
    );
2433
    assert!(b.push("origin", false).is_err());
2434
    // With an identity the policy does not list, the push is rejected by origin.
2435
    let (key_b, id_b) = b
2436
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2437
        .unwrap();
2438
    write(&root.join("b"), "b.txt", b"b2\n");
2439
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
2440
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
2441
    let r = b.push("origin", false).unwrap();
2442
    origin.refresh().unwrap();
2443
    assert!(
2444
        !r[0].ok && r[0].reason.contains("may not update"),
2445
        "{:?}",
2446
        r
2447
    );
2448
2449
    // A grants B (identity handed over as a file) and publishes the policy.
2450
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
2451
    assert_eq!(sp.policy.serial, 2);
2452
    let r = a.push("origin", false).unwrap();
2453
    origin.refresh().unwrap();
2454
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
2455
    // B must fetch the new policy before pushing.
2456
    assert!(b
2457
        .push("origin", false)
2458
        .unwrap_or_else(|e| vec![RefResult {
2459
            name: "main".into(),
2460
            ok: false,
2461
            reason: e.to_string()
2462
        }])
2463
        .iter()
2464
        .all(|x| !x.ok));
2465
    b.pull("origin").unwrap();
2466
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
2467
    let r = b.push("origin", false).unwrap();
2468
    origin.refresh().unwrap();
2469
    assert!(r[0].ok, "{:?}", r);
2470
    // Origin verified B's change under the policy.
2471
    let heads = origin.bookmark_heads().unwrap();
2472
    for h in &heads {
2473
        let c = origin.store().get_change(h).unwrap();
2474
        if c.author == key_b {
2475
            origin
2476
                .change_allowed(
2477
                    h,
2478
                    &origin.current_policy().unwrap().unwrap().1.policy,
2479
                    "main",
2480
                )
2481
                .unwrap();
2482
        }
2483
    }
2484
2485
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
2486
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
2487
    forged.serial = 3;
2488
    forged.roots = vec![key_b];
2489
    let fh = forged.hash();
2490
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
2491
    let forged = SignedPolicy {
2492
        policy: forged,
2493
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
2494
    };
2495
    let r = origin
2496
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
2497
        .unwrap();
2498
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
2499
    let stale = a.current_policy().unwrap().unwrap().1;
2500
    let mut old = stale.clone();
2501
    old.policy.serial = 1;
2502
    let r = origin
2503
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
2504
        .unwrap();
2505
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
2506
2507
    // A revokes B; after B pulls the policy, B's pushes are refused again.
2508
    a.pull("origin").unwrap();
2509
    a.policy_revoke(&key_b).unwrap();
2510
    let r = a.push("origin", false).unwrap();
2511
    origin.refresh().unwrap();
2512
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
2513
    b.pull("origin").unwrap();
2514
    write(&root.join("b"), "b.txt", b"b3\n");
2515
    b.commit("b3", &[]).unwrap();
2516
    let r = b.push("origin", false).unwrap();
2517
    origin.refresh().unwrap();
2518
    assert!(!r[0].ok, "{:?}", r);
2519
2520
    // A clone by a third party receives and verifies everything.
2521
    let c = Repo::clone(&url, &root.join("c"))
2522
        .unwrap()
2523
        .with_home(root.join("home-c"));
2524
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
2525
    assert!(c
2526
        .current_policy()
2527
        .unwrap()
2528
        .unwrap()
2529
        .1
2530
        .policy
2531
        .roots
2532
        .contains(&key_a));
2533
    assert!(!c.snapshot("status").unwrap().changed);
2534
}
2535
2536
/// oxygen#66: a gc says what it is doing, phase by phase.
2537
#[test]
2538
fn gc_reports_its_phases() {
2539
    hermetic();
2540
    let dir = tempfile::tempdir().unwrap();
2541
    let repo = Repo::init(dir.path()).unwrap();
2542
    for i in 0..3 {
2543
        write(
2544
            dir.path(),
2545
            &format!("f{i}.txt"),
2546
            format!("{i}\n").as_bytes(),
2547
        );
2548
        repo.commit(&format!("c{i}"), &[]).unwrap();
2549
    }
2550
    let mut phases = Vec::new();
2551
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
2552
        .unwrap();
2553
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
2554
    assert!(
2555
        phases.iter().any(|p| p.starts_with("pruning")),
2556
        "{phases:?}"
2557
    );
2558
    assert!(
2559
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
2560
        "{phases:?}"
2561
    );
2562
    assert!(
2563
        phases
2564
            .iter()
2565
            .any(|p| p.starts_with("writing the index of ")),
2566
        "{phases:?}"
2567
    );
2568
}
2569
2570
#[test]
2571
fn gc_packs_objects_and_history_still_works() {
2572
    hermetic();
2573
    let dir = tempfile::tempdir().unwrap();
2574
    let root = dir.path();
2575
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2576
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2577
        .unwrap();
2578
    repo.set_user_config("core.sign", "change").unwrap();
2579
    write(root, "a.txt", b"one\n");
2580
    let h1 = repo.commit("one", &[]).unwrap();
2581
    write(root, "a.txt", b"two\n");
2582
    write(root, "big.bin", &vec![0u8; 100_000]);
2583
    let h2 = repo.commit("two", &[]).unwrap();
2584
    // Several snapshots leave superseded working-copy versions behind.
2585
    for i in 0..5 {
2586
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
2587
        repo.snapshot("status").unwrap();
2588
    }
2589
    write(root, "a.txt", b"two\n");
2590
    repo.snapshot("status").unwrap();
2591
    let before = repo.store().list().unwrap();
2592
    assert!(repo.store().loose_count().unwrap() > 0);
2593
2594
    // With the default retention every operation's view is a root: nothing prunes.
2595
    let r = repo.gc(true).unwrap();
2596
    assert_eq!(r.packed.objects, before.len());
2597
    assert_eq!(r.pruned.objects, 0);
2598
    assert_eq!(repo.store().loose_count().unwrap(), 0);
2599
    assert_eq!(repo.store().list().unwrap(), before);
2600
2601
    // With zero retention only the current view is a root: superseded
2602
    // working copies go, everything reachable stays.
2603
    repo.config.set("core.op-retention", "0").unwrap();
2604
    repo.save_config().unwrap();
2605
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
2606
    let r = repo.gc(true).unwrap();
2607
    assert!(r.pruned.objects >= 5, "{r:?}");
2608
    let after = repo.store().list().unwrap();
2609
    assert!(after.len() < before.len());
2610
    assert!(after.contains(&h1) && after.contains(&h2));
2611
    for (_, op) in repo.op_log().unwrap() {
2612
        assert!(!op.command.is_empty(), "operation objects are all kept");
2613
    }
2614
    // Everything still works from the pruned, packed store.
2615
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
2616
    assert!(matches!(
2617
        repo.verify_change(&h2).unwrap(),
2618
        SignatureStatus::Valid { .. }
2619
    ));
2620
    assert_eq!(repo.log().unwrap().len(), 3);
2621
    repo.checkout(&[h1], false, "checkout").unwrap();
2622
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
2623
    repo.checkout(&[h2], false, "checkout").unwrap();
2624
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
2625
    assert!(!repo.snapshot("status").unwrap().changed);
2626
    // Grace period defers pruning of young garbage.
2627
    write(root, "a.txt", b"three\n");
2628
    repo.commit("three", &[]).unwrap();
2629
    let r = repo.gc(false).unwrap();
2630
    assert_eq!(r.pruned.objects, 0);
2631
    assert!(r.pruned.deferred > 0);
2632
    let r = repo.gc(true).unwrap();
2633
    assert!(r.pruned.objects > 0);
2634
    assert_eq!(repo.log().unwrap().len(), 4);
2635
    // Restoring the default retention makes the old views roots again; the
2636
    // working copies they name were pruned, which gc tolerates.
2637
    repo.config.set("core.op-retention", "90").unwrap();
2638
    repo.save_config().unwrap();
2639
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2640
    let r = repo.gc(false).unwrap();
2641
    assert_eq!(r.pruned.objects, 0);
2642
    assert_eq!(repo.log().unwrap().len(), 4);
2643
}
2644
2645
#[test]
2646
fn describe_amend_abandon_heads() {
2647
    hermetic();
2648
    let dir = tempfile::tempdir().unwrap();
2649
    let root = dir.path();
2650
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2651
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2652
        .unwrap();
2653
    repo.set_user_config("core.sign", "change").unwrap();
2654
    write(root, "a.txt", b"one\n");
2655
    let h1 = repo.commit("first", &[]).unwrap();
2656
    write(root, "a.txt", b"one\ntwo\n");
2657
    let h2 = repo.commit("secnod", &[]).unwrap();
2658
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
2659
2660
    // describe: same ChangeId, new hash, bookmark and working copy follow.
2661
    let h2b = repo.describe(&h2, "second").unwrap();
2662
    assert_ne!(h2b, h2);
2663
    let c = repo.store().get_change(&h2b).unwrap();
2664
    assert_eq!(
2665
        (c.change_id, c.message.as_str(), c.deps.clone()),
2666
        (id2, "second", vec![h1])
2667
    );
2668
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
2669
    assert!(matches!(
2670
        repo.verify_change(&h2b).unwrap(),
2671
        SignatureStatus::Valid { .. }
2672
    ));
2673
    let s = repo.snapshot("status").unwrap();
2674
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
2675
    assert_eq!(
2676
        repo.resolve_change(&id2.short(8)).unwrap(),
2677
        h2b,
2678
        "the old object is no longer reachable from the log"
2679
    );
2680
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
2681
    let h1b = repo.describe(&h1, "first, described").unwrap();
2682
    assert_ne!(h1b, h1);
2683
    let heads = repo.bookmark_heads().unwrap();
2684
    assert_eq!(heads.len(), 1);
2685
    let top = repo.store().get_change(&heads[0]).unwrap();
2686
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
2687
    assert!(
2688
        matches!(
2689
            repo.verify_change(&heads[0]).unwrap(),
2690
            SignatureStatus::Valid { .. }
2691
        ),
2692
        "rewritten own change is re-signed"
2693
    );
2694
    let (_, wc) = repo.working_copy().unwrap();
2695
    assert_eq!(
2696
        wc.deps,
2697
        vec![heads[0]],
2698
        "the working copy follows the rewrite"
2699
    );
2700
    assert!(!repo.snapshot("status").unwrap().changed);
2701
    let snap = repo.load_state(&heads).unwrap().materialize();
2702
    assert!(
2703
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
2704
    );
2705
2706
    // amend: fold an edit into the head; the result is one change from h1.
2707
    write(root, "a.txt", b"one\ntwo\nthree\n");
2708
    write(root, "b.txt", b"b\n");
2709
    let h2c = repo.amend(None).unwrap();
2710
    let c = repo.store().get_change(&h2c).unwrap();
2711
    assert_eq!(c.change_id, id2);
2712
    assert_eq!(c.message, "second");
2713
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
2714
    assert_eq!(
2715
        repo.log().unwrap().len(),
2716
        3,
2717
        "working copy, amended head, first"
2718
    );
2719
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
2720
    assert!(
2721
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
2722
    );
2723
    assert!(snap.files.contains_key("b.txt"));
2724
    assert!(!repo.snapshot("status").unwrap().changed);
2725
    assert!(
2726
        repo.amend(None).is_err(),
2727
        "clean working copy and no message"
2728
    );
2729
    let h2d = repo.amend(Some("second, amended")).unwrap();
2730
    assert_eq!(
2731
        repo.store().get_change(&h2d).unwrap().message,
2732
        "second, amended"
2733
    );
2734
2735
    // abandon: the head goes, its content stays as uncommitted work.
2736
    repo.abandon(&h2d).unwrap();
2737
    assert_eq!(
2738
        repo.bookmark_heads().unwrap(),
2739
        vec![h1b],
2740
        "the described first change is the head again"
2741
    );
2742
    let s = repo.snapshot("status").unwrap();
2743
    let paths: Vec<_> = s
2744
        .statuses
2745
        .iter()
2746
        .map(|p| (p.path.as_str(), p.status))
2747
        .collect();
2748
    assert_eq!(
2749
        paths,
2750
        vec![
2751
            ("a.txt", ChangeStatus::Modified),
2752
            ("b.txt", ChangeStatus::Added)
2753
        ]
2754
    );
2755
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
2756
    let h3 = repo.commit("recommitted", &[]).unwrap();
2757
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
2758
    // undo brings the abandoned head back.
2759
    repo.undo().unwrap();
2760
    repo.undo().unwrap();
2761
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
2762
2763
    // Abandoning a non-head whose dependent references its atoms reifies
2764
    // the references (here: a.txt vanishes with it, so the dependent's edit
2765
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
2766
    let base = repo.bookmark_heads().unwrap()[0];
2767
    let base_change = repo.store().get_change(&base).unwrap();
2768
    let h1_now = base_change.deps[0];
2769
    let notes = repo.abandon(&h1_now).unwrap();
2770
    assert!(
2771
        !notes.is_empty(),
2772
        "the dependent's edit of a.txt was reified"
2773
    );
2774
    let heads = repo.bookmark_heads().unwrap();
2775
    let after = repo.load_state(&heads).unwrap().materialize();
2776
    assert!(
2777
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
2778
        "{:?}",
2779
        after.files.keys()
2780
    );
2781
    repo.undo().unwrap();
2782
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
2783
    write(root, "c.txt", b"c\n");
2784
    let hc = repo.commit("c", &[]).unwrap();
2785
    write(root, "d.txt", b"d\n");
2786
    let hd = repo.commit("d", &[hc]).unwrap();
2787
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
2788
    repo.abandon(&hc).unwrap();
2789
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2790
    assert!(!heads.contains(&hc));
2791
    let d_now = heads
2792
        .iter()
2793
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
2794
        .copied()
2795
        .unwrap();
2796
    assert!(
2797
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
2798
        "d inherited c's (empty) dependencies"
2799
    );
2800
    let s = repo.snapshot("status").unwrap();
2801
    assert_eq!(
2802
        s.statuses
2803
            .iter()
2804
            .map(|p| p.path.as_str())
2805
            .collect::<Vec<_>>(),
2806
        vec!["c.txt"],
2807
        "c's content is now uncommitted work"
2808
    );
2809
}
2810
2811
#[test]
2812
fn git_export_mirrors_history() {
2813
    hermetic();
2814
    if std::process::Command::new("git")
2815
        .arg("--version")
2816
        .output()
2817
        .is_err()
2818
    {
2819
        eprintln!("git not installed; skipping");
2820
        return;
2821
    }
2822
    let dir = tempfile::tempdir().unwrap();
2823
    let root = dir.path();
2824
    let mut repo = Repo::init(&root.join("r"))
2825
        .unwrap()
2826
        .with_home(root.join("home"));
2827
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
2828
        .unwrap();
2829
    let r = root.join("r");
2830
    write(&r, "README.md", b"hello\n");
2831
    write(&r, "src/main.rs", b"fn main() {}\n");
2832
    let h1 = repo.commit("first", &[]).unwrap();
2833
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
2834
    write(&r, "logo.png", b"\x89PNG\0\0");
2835
    let h2 = repo.commit("second", &[]).unwrap();
2836
2837
    let git_dir = root.join("mirror.git");
2838
    let rep = repo.git_export(&git_dir).unwrap();
2839
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
2840
    let git = |args: &[&str]| -> String {
2841
        let out = std::process::Command::new("git")
2842
            .arg("-C")
2843
            .arg(&git_dir)
2844
            .args(args)
2845
            .output()
2846
            .unwrap();
2847
        assert!(
2848
            out.status.success(),
2849
            "{}",
2850
            String::from_utf8_lossy(&out.stderr)
2851
        );
2852
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2853
    };
2854
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
2855
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
2856
    assert_eq!(git(&["show", "main:README.md"]), "hello");
2857
    let body = git(&["log", "-1", "--format=%B", "main"]);
2858
    assert!(
2859
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
2860
        "{body}"
2861
    );
2862
    assert!(body.contains("Change-Id: "), "{body}");
2863
    assert_eq!(
2864
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
2865
        "Ada Lovelace <[email protected]>"
2866
    );
2867
    assert_eq!(
2868
        git(&["ls-tree", "--name-only", "main"]),
2869
        "README.md\nlogo.png\nsrc"
2870
    );
2871
2872
    // Re-export is incremental.
2873
    let rep = repo.git_export(&git_dir).unwrap();
2874
    assert_eq!((rep.exported, rep.skipped), (0, 2));
2875
2876
    // An independent change makes two heads; the next state is one more
2877
    // commit on the linear branch whose tree is the union.
2878
    repo.checkout(&[h1], false, "checkout").unwrap();
2879
    write(&r, "other.txt", b"o\n");
2880
    let h3 = repo.commit("third", &[]).unwrap();
2881
    let rep = repo.git_export(&git_dir).unwrap();
2882
    assert_eq!((rep.exported, rep.heads), (1, 2));
2883
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
2884
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
2885
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
2886
    assert_eq!(git(&["show", "main:other.txt"]), "o");
2887
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
2888
    assert_eq!(
2889
        git(&["ls-tree", "--name-only", "main"]),
2890
        "README.md\nlogo.png\nother.txt\nsrc"
2891
    );
2892
    let body = git(&["log", "-1", "--format=%B", "main"]);
2893
    assert!(
2894
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
2895
        "{body}"
2896
    );
2897
    // A rewrite is a new state whose one new change is the rewritten one.
2898
    repo.describe(&h3, "third, described").unwrap();
2899
    let rep = repo.git_export(&git_dir).unwrap();
2900
    assert_eq!(rep.exported, 1);
2901
    assert_eq!(
2902
        git(&["log", "-1", "--format=%s", "main"]),
2903
        "third, described"
2904
    );
2905
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
2906
    let _ = h2;
2907
}
2908
2909
#[test]
2910
fn git_import_reproduces_trees() {
2911
    git_import_reproduces_trees_with(None);
2912
}
2913
2914
/// The same import with every merge rendered in batches of one file
2915
/// (oxygen#25): what a merge onto a base of thousands of files takes.
2916
#[test]
2917
fn git_import_reproduces_trees_in_batches() {
2918
    git_import_reproduces_trees_with(Some(1));
2919
}
2920
2921
fn git_import_reproduces_trees_with(batch: Option<usize>) {
2922
    crate::repo::git::set_merge_batch_for_tests(batch);
2923
    hermetic();
2924
    if std::process::Command::new("git")
2925
        .arg("--version")
2926
        .output()
2927
        .is_err()
2928
    {
2929
        eprintln!("git not installed; skipping");
2930
        return;
2931
    }
2932
    let dir = tempfile::tempdir().unwrap();
2933
    let root = dir.path();
2934
    let g = root.join("src.git");
2935
    fs::create_dir_all(&g).unwrap();
2936
    let git = |args: &[&str]| -> String {
2937
        let out = std::process::Command::new("git")
2938
            .arg("-C")
2939
            .arg(&g)
2940
            .args([
2941
                "-c",
2942
                "user.name=Grace",
2943
                "-c",
2944
                "[email protected]",
2945
                "-c",
2946
                "commit.gpgsign=false",
2947
            ])
2948
            .args(args)
2949
            .output()
2950
            .unwrap();
2951
        assert!(
2952
            out.status.success(),
2953
            "git {args:?}: {}",
2954
            String::from_utf8_lossy(&out.stderr)
2955
        );
2956
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2957
    };
2958
    git(&["init", "-q", "-b", "main"]);
2959
    write(&g, "README.md", b"# Hi\n");
2960
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
2961
    git(&["add", "."]);
2962
    git(&["commit", "-q", "-m", "initial"]);
2963
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2964
    write(&g, "run.sh", b"#!/bin/sh\n");
2965
    #[cfg(unix)]
2966
    {
2967
        use std::os::unix::fs::PermissionsExt;
2968
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
2969
    }
2970
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
2971
    git(&["add", "."]);
2972
    git(&[
2973
        "commit",
2974
        "-q",
2975
        "-m",
2976
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
2977
    ]);
2978
    // A branch that edits README, merged back with a conflict-free merge.
2979
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
2980
    write(&g, "README.md", b"# Hi\n\nMore.\n");
2981
    git(&["commit", "-q", "-am", "readme"]);
2982
    git(&["checkout", "-q", "main"]);
2983
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
2984
    // A branch from the initial commit inserting at the same place as
2985
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
2986
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
2987
    git(&["checkout", "-q", "-b", "clash", &initial]);
2988
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
2989
    git(&["commit", "-q", "-am", "clash"]);
2990
    git(&["checkout", "-q", "main"]);
2991
    // Expected to stop at the conflict, so its status is ignored; the
2992
    // identity is passed as for every other git call here, or a machine
2993
    // without one refuses to start the merge at all.
2994
    let _ = std::process::Command::new("git")
2995
        .arg("-C")
2996
        .arg(&g)
2997
        .args([
2998
            "-c",
2999
            "user.name=Grace",
3000
            "-c",
3001
            "[email protected]",
3002
            "merge",
3003
            "-q",
3004
            "clash",
3005
        ])
3006
        .output();
3007
    assert!(
3008
        g.join(".git/MERGE_HEAD").exists(),
3009
        "the clash merge stopped at its conflict"
3010
    );
3011
    write(
3012
        &g,
3013
        "src/lib.rs",
3014
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
3015
    );
3016
    git(&["add", "."]);
3017
    git(&["commit", "-q", "-m", "resolve clash"]);
3018
    git(&["rm", "-q", "logo.png"]);
3019
    git(&["commit", "-q", "-m", "drop logo"]);
3020
    // A rename with a small edit is imported as a move of the same node.
3021
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
3022
    write(
3023
        &g,
3024
        "src/lib2.rs",
3025
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
3026
    );
3027
    git(&["add", "."]);
3028
    git(&["commit", "-q", "-m", "rename lib"]);
3029
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
3030
    // run.sh is the same as in the first parent's tree, but the merged
3031
    // change touched it, so the importer must compare it, not skip it.
3032
    git(&["checkout", "-q", "-b", "discarded"]);
3033
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
3034
    git(&["commit", "-q", "-am", "discarded edit"]);
3035
    git(&["checkout", "-q", "main"]);
3036
    git(&[
3037
        "merge",
3038
        "-q",
3039
        "-s",
3040
        "ours",
3041
        "-m",
3042
        "merge discarded, keeping ours",
3043
        "discarded",
3044
    ]);
3045
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
3046
3047
    let dest = root.join("oxy");
3048
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3049
    let rep = repo.import_git(&g, "main").unwrap();
3050
    assert_eq!(rep.commits, expected_count);
3051
    assert_eq!(rep.merges, 3);
3052
    assert_eq!(
3053
        fs::read(dest.join("run.sh")).unwrap(),
3054
        b"#!/bin/sh\n",
3055
        "the ours merge kept main's run.sh"
3056
    );
3057
    let v = repo.verify_git_import(&g, "main").unwrap();
3058
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
3059
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
3060
    // The working copy equals the Git tree at main.
3061
    assert_eq!(
3062
        fs::read(dest.join("src/lib2.rs")).unwrap(),
3063
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
3064
    );
3065
    assert!(!dest.join("src/lib.rs").exists());
3066
    assert_eq!(
3067
        fs::read(dest.join("README.md")).unwrap(),
3068
        b"# Hi\n\nMore.\n"
3069
    );
3070
    assert!(!dest.join("logo.png").exists());
3071
    #[cfg(unix)]
3072
    {
3073
        use std::os::unix::fs::PermissionsExt;
3074
        assert!(
3075
            fs::metadata(dest.join("run.sh"))
3076
                .unwrap()
3077
                .permissions()
3078
                .mode()
3079
                & 0o111
3080
                != 0
3081
        );
3082
    }
3083
    assert!(
3084
        !repo.snapshot("status").unwrap().changed,
3085
        "clean after import"
3086
    );
3087
    let heads = repo.bookmark_heads().unwrap();
3088
    let st = repo.load_state(&heads).unwrap();
3089
    assert!(!st.materialize().is_conflicted());
3090
    assert_eq!(st.len(), expected_count);
3091
    let tip = repo
3092
        .log()
3093
        .unwrap()
3094
        .into_iter()
3095
        .find(|e| e.change.message.starts_with("rename lib"))
3096
        .unwrap();
3097
    let c = repo.store().get_change(&tip.hash).unwrap();
3098
    assert!(
3099
        c.tree_ops
3100
            .iter()
3101
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
3102
        "{:?}",
3103
        c.tree_ops
3104
    );
3105
    assert!(!c
3106
        .tree_ops
3107
        .iter()
3108
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
3109
    // Messages carry Git trailers; the Change-Id trailer was honoured.
3110
    let log = repo.log().unwrap();
3111
    let second = log
3112
        .iter()
3113
        .find(|e| e.change.message.starts_with("second"))
3114
        .unwrap();
3115
    assert_eq!(
3116
        second.change.change_id,
3117
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
3118
    );
3119
    assert!(second
3120
        .change
3121
        .message
3122
        .contains("Git-Author: Grace <[email protected]>"));
3123
    let resolve = log
3124
        .iter()
3125
        .find(|e| e.change.message.starts_with("resolve clash"))
3126
        .unwrap();
3127
    assert_eq!(
3128
        resolve.change.kind,
3129
        ChangeKind::Resolution,
3130
        "a conflicting Git merge becomes a resolution"
3131
    );
3132
    // Re-importing into another fresh repository gives the same ChangeIds.
3133
    let repo2 = Repo::init(&root.join("oxy2"))
3134
        .unwrap()
3135
        .with_home(root.join("home"));
3136
    repo2.import_git(&g, "main").unwrap();
3137
    // New nodes' identifiers derive from the commit (spec §23), so the
3138
    // re-import is not just the same ChangeIds but the same changes.
3139
    assert_eq!(
3140
        repo2.bookmark_heads().unwrap(),
3141
        repo.bookmark_heads().unwrap()
3142
    );
3143
    let ids: BTreeSet<ChangeId> = repo
3144
        .log()
3145
        .unwrap()
3146
        .iter()
3147
        .filter(|e| !e.is_working_copy)
3148
        .map(|e| e.change.change_id)
3149
        .collect();
3150
    let ids2: BTreeSet<ChangeId> = repo2
3151
        .log()
3152
        .unwrap()
3153
        .iter()
3154
        .filter(|e| !e.is_working_copy)
3155
        .map(|e| e.change.change_id)
3156
        .collect();
3157
    assert_eq!(ids, ids2);
3158
    // Round trip back out to Git reproduces the tip tree.
3159
    let mirror = root.join("mirror.git");
3160
    repo.git_export(&mirror).unwrap();
3161
    let out = std::process::Command::new("git")
3162
        .arg("-C")
3163
        .arg(&mirror)
3164
        .args(["show", "main:src/lib2.rs"])
3165
        .output()
3166
        .unwrap();
3167
    assert_eq!(
3168
        String::from_utf8_lossy(&out.stdout),
3169
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
3170
    );
3171
    let out = std::process::Command::new("git")
3172
        .arg("-C")
3173
        .arg(&mirror)
3174
        .args(["show", "main:src/lib.rs"])
3175
        .output()
3176
        .unwrap();
3177
    assert!(
3178
        !out.status.success(),
3179
        "the old path is gone from the export"
3180
    );
3181
}
3182
3183
#[test]
3184
fn checkpoints_accelerate_loading_and_stay_correct() {
3185
    hermetic();
3186
    let dir = tempfile::tempdir().unwrap();
3187
    let root = dir.path();
3188
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3189
    repo.config.set("core.checkpoint-interval", "5").unwrap();
3190
    repo.save_config().unwrap();
3191
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
3192
    let mut hashes = Vec::new();
3193
    for i in 0..12 {
3194
        write(
3195
            root,
3196
            "a.txt",
3197
            format!(
3198
                "{}\n",
3199
                (0..=i)
3200
                    .map(|k| k.to_string())
3201
                    .collect::<Vec<_>>()
3202
                    .join("\n")
3203
            )
3204
            .as_bytes(),
3205
        );
3206
        write(root, &format!("f{i}.txt"), b"x\n");
3207
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
3208
    }
3209
    let (_, cp) = repo
3210
        .latest_checkpoint("main")
3211
        .unwrap()
3212
        .expect("automatic checkpoint");
3213
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
3214
    // Loading through the checkpoint equals loading everything.
3215
    let heads = repo.bookmark_heads().unwrap();
3216
    let fast = repo.load_state(&heads).unwrap();
3217
    let full = repo.load_state_full(&heads).unwrap();
3218
    assert_eq!(fast.len(), full.len());
3219
    assert_eq!(fast.heads(), full.heads());
3220
    let (a, b) = (fast.materialize(), full.materialize());
3221
    assert_eq!(
3222
        a.files.keys().collect::<Vec<_>>(),
3223
        b.files.keys().collect::<Vec<_>>()
3224
    );
3225
    for (p, f) in &a.files {
3226
        assert_eq!(f.content, b.files[p].content, "{p}");
3227
    }
3228
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
3229
    // A head set that does not contain the checkpoint's heads falls back.
3230
    assert!(repo
3231
        .load_state_checkpointed(&[hashes[0]])
3232
        .unwrap()
3233
        .is_none());
3234
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
3235
    // Everything else keeps working on top of the checkpoint.
3236
    assert!(!repo.snapshot("status").unwrap().changed);
3237
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
3238
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
3239
    let (r, n, bytes) = repo.checkpoint().unwrap();
3240
    assert!(n >= 12 && bytes > 0);
3241
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
3242
    write(root, "a.txt", b"after\n");
3243
    let h_after = repo.commit("after", &[]).unwrap();
3244
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
3245
    assert!(st.contains(&h_after));
3246
    assert!(
3247
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
3248
    );
3249
    assert_eq!(repo.log().unwrap().len(), 14);
3250
    // Checkpoints survive gc.
3251
    repo.gc(true).unwrap();
3252
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
3253
    assert!(repo
3254
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
3255
        .unwrap()
3256
        .is_some());
3257
}
3258
3259
#[test]
3260
fn quick_status_for_prompts() {
3261
    hermetic();
3262
    let dir = tempfile::tempdir().unwrap();
3263
    let root = dir.path();
3264
    let origin = Repo::init(&root.join("origin")).unwrap();
3265
    let url = root.join("origin").to_string_lossy().to_string();
3266
    let a = Repo::clone(&url, &root.join("a"))
3267
        .unwrap()
3268
        .with_home(root.join("home"));
3269
    let ops_before = a.op_log().unwrap().len();
3270
    let info = a.quick_status().unwrap();
3271
    assert_eq!(
3272
        (
3273
            info.bookmark.as_str(),
3274
            info.heads,
3275
            info.dirty,
3276
            info.conflicted,
3277
            info.ahead,
3278
            info.behind
3279
        ),
3280
        ("main", 0, false, false, Some(0), Some(0))
3281
    );
3282
    write(&root.join("a"), "f.txt", b"f\n");
3283
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
3284
    assert_eq!(
3285
        a.op_log().unwrap().len(),
3286
        ops_before,
3287
        "quick_status records nothing"
3288
    );
3289
    // A snapshotted but uncommitted change is still dirty.
3290
    a.snapshot("status").unwrap();
3291
    assert!(a.quick_status().unwrap().dirty);
3292
    a.commit("f", &[]).unwrap();
3293
    let info = a.quick_status().unwrap();
3294
    assert!(!info.dirty, "clean right after a commit");
3295
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
3296
    assert_eq!(
3297
        info.format("%b %c%d%x%A%D"),
3298
        format!("main {}+1", info.change_id)
3299
    );
3300
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
3301
    // Touching a file without changing it is not dirty; changing content of
3302
    // the same size is.
3303
    let p = root.join("a/f.txt");
3304
    let content = fs::read(&p).unwrap();
3305
    fs::write(&p, &content).unwrap();
3306
    assert!(!a.quick_status().unwrap().dirty);
3307
    fs::write(&p, b"g\n").unwrap();
3308
    assert!(a.quick_status().unwrap().dirty);
3309
    fs::write(&p, b"f\n").unwrap();
3310
    // Push, then a second clone commits and pushes: we are behind.
3311
    assert!(a.push("origin", false).unwrap()[0].ok);
3312
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
3313
    let b = Repo::clone(&url, &root.join("b"))
3314
        .unwrap()
3315
        .with_home(root.join("home-b"));
3316
    write(&root.join("b"), "g.txt", b"g\n");
3317
    b.commit("g", &[]).unwrap();
3318
    b.push("origin", false).unwrap();
3319
    a.fetch("origin").unwrap();
3320
    let info = a.quick_status().unwrap();
3321
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
3322
    assert_eq!(info.format("%A%D"), "-1");
3323
    let _ = origin;
3324
}
3325
3326
#[test]
3327
fn lazy_blobs_are_fetched_on_first_read() {
3328
    hermetic();
3329
    let dir = tempfile::tempdir().unwrap();
3330
    let root = dir.path();
3331
    let origin_dir = root.join("origin");
3332
    let origin = Repo::init(&origin_dir)
3333
        .unwrap()
3334
        .with_home(root.join("home"));
3335
    let url = origin_dir.to_string_lossy().to_string();
3336
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
3337
    write(&origin_dir, "big.bin", &big);
3338
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
3339
    write(&origin_dir, "t.txt", b"t\n");
3340
    let h = origin.commit("blobs", &[]).unwrap();
3341
    let big_ref = Repo::blob_ref(&big);
3342
3343
    // Fetch only (no checkout) with a filter: the big blob stays absent.
3344
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
3345
        .unwrap()
3346
        .with_home(root.join("home"));
3347
    let a = {
3348
        let mut a = a;
3349
        a.config.set("remote.origin.url", &url).unwrap();
3350
        a.config.set("filter.max-blob", "100K").unwrap();
3351
        a.save_config().unwrap();
3352
        a
3353
    };
3354
    assert_eq!(a.config.max_blob, Some(100 * 1024));
3355
    a.fetch("origin").unwrap();
3356
    assert!(a.store().has(&h));
3357
    assert!(!a.store().has(&big_ref), "withheld");
3358
    assert!(
3359
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
3360
        "small blob came along"
3361
    );
3362
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
3363
3364
    // status and commit do not need it: adopt the state, edit a text file, commit.
3365
    let (op_ref, op) = a.head_op().unwrap();
3366
    let mut view = op.view.clone();
3367
    view.bookmarks.insert(
3368
        "main".into(),
3369
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
3370
    );
3371
    a.record_op(&[op_ref], "adopt", view).unwrap();
3372
    // Checkout reads the blob lazily, which fetches it.
3373
    a.checkout(&[h], true, "checkout").unwrap();
3374
    assert!(a.store().has(&big_ref), "fetched on first read");
3375
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
3376
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
3377
    write(&root.join("a"), "t.txt", b"t2\n");
3378
    a.commit("text edit", &[]).unwrap();
3379
3380
    // clone --max-blob records the filter; the checkout fetches lazily.
3381
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
3382
    assert_eq!(b.config.max_blob, Some(1024));
3383
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
3384
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
3385
    assert!(parse_size("lots").is_err());
3386
}
3387
3388
#[test]
3389
fn sparse_checkout_materializes_only_chosen_paths() {
3390
    hermetic();
3391
    let dir = tempfile::tempdir().unwrap();
3392
    let root = dir.path();
3393
    let origin_dir = root.join("origin");
3394
    let origin = Repo::init(&origin_dir)
3395
        .unwrap()
3396
        .with_home(root.join("home"));
3397
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
3398
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
3399
    write(&origin_dir, "docs/guide.md", b"# guide\n");
3400
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
3401
    write(&origin_dir, "docs/logo.png", &logo);
3402
    write(&origin_dir, "README.md", b"# top\n");
3403
    let h1 = origin.commit("tree", &[]).unwrap();
3404
    let url = origin_dir.to_string_lossy().to_string();
3405
3406
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
3407
        .unwrap()
3408
        .with_home(root.join("home"));
3409
    assert_eq!(a.config.sparse_paths, vec!["src"]);
3410
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
3411
    assert!(root.join("a/src/main.rs").exists());
3412
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
3413
    assert!(
3414
        !a.store().has(&Repo::blob_ref(&logo)),
3415
        "out-of-scope blob never fetched"
3416
    );
3417
    assert!(
3418
        !a.snapshot("status").unwrap().changed,
3419
        "out-of-scope files are not removals"
3420
    );
3421
    assert!(!a.quick_status().unwrap().dirty);
3422
3423
    // Edits in scope commit normally and keep the rest of the tree intact.
3424
    write(
3425
        &root.join("a"),
3426
        "src/lib.rs",
3427
        b"pub fn a() {}\npub fn b() {}\n",
3428
    );
3429
    let h2 = a.commit("edit lib", &[]).unwrap();
3430
    let st = a.load_state(&[h2]).unwrap().materialize();
3431
    assert!(
3432
        st.files.contains_key("docs/guide.md"),
3433
        "the state still has everything"
3434
    );
3435
    assert!(a.push("origin", false).unwrap()[0].ok);
3436
    origin.refresh().unwrap();
3437
    // Files created outside the scope are ignored by status.
3438
    write(&root.join("a"), "docs/new.md", b"ignored\n");
3439
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
3440
3441
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
3442
    let mut a = a;
3443
    a.config.set("filter.paths", "src,docs").unwrap();
3444
    a.save_config().unwrap();
3445
    let r = a
3446
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
3447
        .unwrap();
3448
    assert!(r.written >= 2);
3449
    assert_eq!(
3450
        fs::read(root.join("a/docs/logo.png")).unwrap(),
3451
        logo,
3452
        "now fetched lazily"
3453
    );
3454
    assert!(!root.join("a/README.md").exists());
3455
    // Origin sees the change made under a sparse checkout with the full tree intact.
3456
    origin.pull("origin").err();
3457
    let full = origin
3458
        .load_state(&origin.bookmark_heads().unwrap())
3459
        .unwrap()
3460
        .materialize();
3461
    assert!(
3462
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
3463
    );
3464
    assert!(full.files.contains_key("README.md"));
3465
    let _ = h1;
3466
}
3467
3468
/// #137: a depth-0 clone takes no change, so the blobs of the state's
3469
/// binary files came with nothing and the checkout failed ("object … not
3470
/// found"); they are fetched with the checkpoint, or left lazy under
3471
/// `--max-blob`.
3472
#[test]
3473
fn a_depth_0_clone_brings_its_binary_files() {
3474
    hermetic();
3475
    let dir = tempfile::tempdir().unwrap();
3476
    let root = dir.path();
3477
    let origin_dir = root.join("origin");
3478
    let origin = Repo::init(&origin_dir)
3479
        .unwrap()
3480
        .with_home(root.join("home"));
3481
    let png: Vec<u8> = (0..4000u32)
3482
        .map(|i| (i * 7 % 251) as u8)
3483
        .chain([0, 0xff])
3484
        .collect();
3485
    // The logo comes with a.txt's first line, and the head edits that line,
3486
    // so the change that set the logo is below the head, not a head itself.
3487
    write(&origin_dir, "logo.png", &png);
3488
    write(&origin_dir, "a.txt", b"first\n");
3489
    origin.commit("logo", &[]).unwrap();
3490
    write(&origin_dir, "a.txt", b"later\n");
3491
    origin.commit("later", &[]).unwrap();
3492
    assert_eq!(origin.bookmark_heads().unwrap().len(), 1);
3493
    let url = origin_dir.to_string_lossy().to_string();
3494
    Repo::clone_shallow(&url, &root.join("a"), 0, None, &[]).unwrap();
3495
    assert_eq!(fs::read(root.join("a/logo.png")).unwrap(), png);
3496
    let lazy = Repo::clone_shallow(&url, &root.join("b"), 0, Some(0), &[]).unwrap();
3497
    assert_eq!(fs::read(root.join("b/a.txt")).unwrap(), b"later\n");
3498
    let blob = {
3499
        let heads = lazy.bookmark_heads().unwrap();
3500
        let st = lazy.load_state_history(&heads).unwrap();
3501
        st.opaque_nodes()
3502
            .iter()
3503
            .flat_map(|n| st.live_blobs(n))
3504
            .next()
3505
            .unwrap()
3506
    };
3507
    assert_eq!(lazy.read_blob(&blob).unwrap(), png, "fetched on read");
3508
    // Depth 0 takes no change: the head is the boundary; the log comes from
3509
    // the checkpoint; a change on top commits and pushes.
3510
    let mut a = Repo::open(&root.join("a"))
3511
        .unwrap()
3512
        .with_home(root.join("home"));
3513
    let head = origin.bookmark_heads().unwrap()[0];
3514
    assert!(!a.store().has(&head), "no change fetched");
3515
    assert!(a.boundary().contains(&head));
3516
    assert_eq!(
3517
        a.log()
3518
            .unwrap()
3519
            .iter()
3520
            .filter(|e| !e.is_working_copy)
3521
            .count(),
3522
        2,
3523
        "the log from the checkpoint"
3524
    );
3525
    write(&root.join("a"), "a.txt", b"later\nmine\n");
3526
    a.config.set("remote.origin.url", &url).unwrap();
3527
    a.save_config().unwrap();
3528
    let mine = a.commit("mine", &[]).unwrap();
3529
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
3530
    origin.refresh().unwrap();
3531
    assert!(origin.store().has(&mine));
3532
    assert_eq!(origin.bookmark_heads().unwrap(), vec![mine]);
3533
    // And pulls what comes after.
3534
    origin
3535
        .checkout(&origin.bookmark_heads().unwrap(), false, "co")
3536
        .unwrap();
3537
    write(&origin_dir, "a.txt", b"later\nmine\ntheirs\n");
3538
    origin.snapshot("t").unwrap();
3539
    origin.commit("theirs", &[]).unwrap();
3540
    a.pull("origin").unwrap();
3541
    assert_eq!(
3542
        fs::read(root.join("a/a.txt")).unwrap(),
3543
        b"later\nmine\ntheirs\n"
3544
    );
3545
}
3546
3547
#[test]
3548
fn shallow_clone_and_deepen() {
3549
    hermetic();
3550
    let dir = tempfile::tempdir().unwrap();
3551
    let root = dir.path();
3552
    let origin_dir = root.join("origin");
3553
    let origin = Repo::init(&origin_dir)
3554
        .unwrap()
3555
        .with_home(root.join("home"));
3556
    let mut hashes = Vec::new();
3557
    for i in 0..8 {
3558
        write(
3559
            &origin_dir,
3560
            "a.txt",
3561
            format!(
3562
                "{}\n",
3563
                (0..=i)
3564
                    .map(|k| k.to_string())
3565
                    .collect::<Vec<_>>()
3566
                    .join("\n")
3567
            )
3568
            .as_bytes(),
3569
        );
3570
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
3571
    }
3572
    let url = origin_dir.to_string_lossy().to_string();
3573
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
3574
        .unwrap()
3575
        .with_home(root.join("home"));
3576
    assert!(a.is_shallow());
3577
    assert_eq!(
3578
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
3579
        "0\n1\n2\n3\n4\n5\n6\n7\n"
3580
    );
3581
    assert!(
3582
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
3583
        "three levels present"
3584
    );
3585
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
3586
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
3587
    assert_eq!(
3588
        a.log().unwrap().len(),
3589
        9,
3590
        "the log shows every change from the checkpoint's metadata"
3591
    );
3592
    assert!(!a.snapshot("status").unwrap().changed);
3593
    assert_eq!(a.quick_status().unwrap().heads, 1);
3594
3595
    // Work continues on top of the shallow history and pushes back.
3596
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
3597
    let h_new = a.commit("c8", &[]).unwrap();
3598
    assert!(a.push("origin", false).unwrap()[0].ok);
3599
    origin.refresh().unwrap();
3600
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
3601
    // Fetching new work from origin into the shallow clone works too.
3602
    write(&origin_dir, "b.txt", b"b\n");
3603
    origin.pull("origin").err();
3604
    let (_, wc) = origin.working_copy().unwrap();
3605
    let _ = wc;
3606
    origin
3607
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
3608
        .unwrap();
3609
    write(&origin_dir, "b.txt", b"b\n");
3610
    let h_b = origin.commit("b", &[]).unwrap();
3611
    let pr = a.pull("origin").unwrap();
3612
    assert!(pr.changed);
3613
    assert!(a.store().has(&h_b));
3614
    assert!(root.join("a/b.txt").exists());
3615
3616
    // Deepening fetches older history until the boundary is gone.
3617
    // Every commit also depends on the change that created the file, so two
3618
    // levels below the boundary hold h4, h3, and the root.
3619
    assert!(a.deepen("origin", 2).unwrap() >= 2);
3620
    assert!(a.store().has(&hashes[3]));
3621
    assert!(a.is_shallow());
3622
    a.deepen("origin", 100).unwrap();
3623
    assert!(!a.is_shallow(), "boundary reached the root");
3624
    assert!(a.store().has(&hashes[0]));
3625
    assert_eq!(
3626
        a.load_state_full(&a.bookmark_heads().unwrap())
3627
            .unwrap()
3628
            .len(),
3629
        10
3630
    );
3631
}
3632
3633
#[test]
3634
fn a_tag_is_withdrawn_by_a_signed_withdrawal() {
3635
    hermetic();
3636
    let dir = tempfile::tempdir().unwrap();
3637
    let root = dir.path();
3638
    let origin = Repo::init(&root.join("origin")).unwrap();
3639
    let url = root.join("origin").to_string_lossy().to_string();
3640
    let mut a = Repo::clone(&url, &root.join("a"))
3641
        .unwrap()
3642
        .with_home(root.join("home-a"));
3643
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
3644
        .unwrap();
3645
    write(&root.join("a"), "f.txt", b"1\n");
3646
    let h1 = a.commit("one", &[]).unwrap();
3647
    a.tag_create("v1", &[h1], "first release").unwrap();
3648
    a.tag_create("v2", &[h1], "").unwrap();
3649
    a.policy_init().unwrap();
3650
    a.push("origin", false).unwrap();
3651
    origin.refresh().unwrap();
3652
    let original = a
3653
        .tag_refs()
3654
        .unwrap()
3655
        .into_iter()
3656
        .find(|t| t.name == "v1")
3657
        .unwrap();
3658
    let b = Repo::clone(&url, &root.join("b"))
3659
        .unwrap()
3660
        .with_home(root.join("home-b"));
3661
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
3662
3663
    // A key the policy does not let create the tag may not withdraw it.
3664
    let mut c = Repo::clone(&url, &root.join("c"))
3665
        .unwrap()
3666
        .with_home(root.join("home-c"));
3667
    c.create_identity("Cy", "[email protected]", IdentityScope::User)
3668
        .unwrap();
3669
    let r = c.push_delete("origin", "tags/v1").unwrap();
3670
    assert!(
3671
        !r[0].ok && r[0].reason.contains("may not withdraw"),
3672
        "{r:?}"
3673
    );
3674
    assert_eq!(c.tag_heads("v1").unwrap(), None, "withdrawn there first");
3675
    origin.refresh().unwrap();
3676
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
3677
3678
    // Its creator's key may: the tag goes, the withdrawal stays.
3679
    let r = a.push_delete("origin", "tags/v1").unwrap();
3680
    assert!(r[0].ok && r[0].reason == "withdrawn", "{r:?}");
3681
    origin.refresh().unwrap();
3682
    assert_eq!(origin.tag_heads("v1").unwrap(), None);
3683
    assert_eq!(a.tag_heads("v1").unwrap(), None);
3684
    assert!(origin.tag_withdrawal("v1").unwrap().is_some());
3685
    assert!(origin.tag_attest("v1").unwrap().is_some(), "kept beside it");
3686
    let refs = origin.remote_refs().unwrap();
3687
    assert!(refs.tags.iter().all(|t| t.name != "v1"));
3688
    assert_eq!(refs.withdrawn.len(), 1);
3689
    let r = a.push_delete("origin", "tags/v1").unwrap();
3690
    assert!(r[0].ok && r[0].reason == "already withdrawn", "{r:?}");
3691
3692
    // A fetch withdraws it too, and the name is never used again.
3693
    let rep = b.fetch("origin").unwrap();
3694
    assert_eq!(rep.withdrawn_tags, vec!["v1".to_string()]);
3695
    assert_eq!(b.tag_heads("v1").unwrap(), None);
3696
    assert!(b.tag_create("v1", &[h1], "").is_err());
3697
    let r = origin
3698
        .receive_push(Bundle::default(), vec![], None, vec![original])
3699
        .unwrap();
3700
    assert!(!r[0].ok && r[0].reason.contains("withdrawn"), "{r:?}");
3701
3702
    // `oxy tag delete`, then a plain push, sends it.
3703
    a.tag_delete("v2", "tagged too early").unwrap();
3704
    let r = a.push("origin", false).unwrap();
3705
    assert!(
3706
        r.iter()
3707
            .any(|x| x.name == "tags/v2" && x.ok && x.reason == "withdrawn"),
3708
        "{r:?}"
3709
    );
3710
    origin.refresh().unwrap();
3711
    assert_eq!(origin.tag_heads("v2").unwrap(), None);
3712
    let (_, w) = origin.tag_withdrawal("v2").unwrap().unwrap();
3713
    assert!(
3714
        matches!(&w.attest.body, AttestBody::Untag { reason, .. } if reason == "tagged too early")
3715
    );
3716
}
3717
3718
#[test]
3719
fn tags_are_immutable_named_states_and_travel() {
3720
    hermetic();
3721
    let dir = tempfile::tempdir().unwrap();
3722
    let root = dir.path();
3723
    let origin = Repo::init(&root.join("origin")).unwrap();
3724
    let url = root.join("origin").to_string_lossy().to_string();
3725
    let mut a = Repo::clone(&url, &root.join("a"))
3726
        .unwrap()
3727
        .with_home(root.join("home-a"));
3728
    let (key_a, _) = a
3729
        .create_identity("Ada", "[email protected]", IdentityScope::User)
3730
        .unwrap();
3731
    write(&root.join("a"), "f.txt", b"1\n");
3732
    let h1 = a.commit("one", &[]).unwrap();
3733
    write(&root.join("a"), "f.txt", b"1\n2\n");
3734
    let h2 = a.commit("two", &[]).unwrap();
3735
3736
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
3737
    assert_eq!(
3738
        (t.heads.clone(), t.signer.as_deref()),
3739
        (vec![h1], Some("Ada"))
3740
    );
3741
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
3742
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
3743
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
3744
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
3745
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
3746
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
3747
    assert_eq!(sa.sigs[0].key, key_a);
3748
    // Without a policy every client is sent every tag, whatever features
3749
    // it declares (oxygen#131).
3750
    let mut refs = a.remote_refs().unwrap();
3751
    a.refs_for_client(&mut refs, None);
3752
    assert_eq!(refs.tags.len(), 1);
3753
    // Checkout by tag.
3754
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
3755
        .unwrap();
3756
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
3757
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
3758
        .unwrap();
3759
3760
    // Push carries the tag; a second attestation for the name is refused.
3761
    let r = a.push("origin", false).unwrap();
3762
    origin.refresh().unwrap();
3763
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
3764
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
3765
    let mut forged = a
3766
        .tag_refs()
3767
        .unwrap()
3768
        .into_iter()
3769
        .find(|t| t.name == "v1")
3770
        .unwrap();
3771
    forged.state = origin
3772
        .store()
3773
        .put_state(&StateObject::new(vec![h2]))
3774
        .unwrap();
3775
    forged.heads = vec![h2];
3776
    forged.attestation = None;
3777
    let r = origin
3778
        .receive_push(Bundle::default(), vec![], None, vec![forged])
3779
        .unwrap();
3780
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
3781
3782
    // A clone gets the tag; a later tag arrives on fetch.
3783
    let b = Repo::clone(&url, &root.join("b"))
3784
        .unwrap()
3785
        .with_home(root.join("home-b"));
3786
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
3787
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
3788
    a.tag_create("v2", &[h2], "second").unwrap();
3789
    a.push("origin", false).unwrap();
3790
    origin.refresh().unwrap();
3791
    let rep = b.fetch("origin").unwrap();
3792
    assert_eq!(rep.new_tags, 1);
3793
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
3794
3795
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
3796
    a.policy_init().unwrap();
3797
    a.push("origin", false).unwrap();
3798
    origin.refresh().unwrap();
3799
    let unattested = crate::protocol::TagRef::new(
3800
        "v3".into(),
3801
        origin
3802
            .store()
3803
            .put_state(&StateObject::new(vec![h2]))
3804
            .unwrap(),
3805
        vec![h2],
3806
        None,
3807
    );
3808
    let r = origin
3809
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
3810
        .unwrap();
3811
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
3812
    a.tag_create("v3", &[h2], "").unwrap();
3813
    let r = a.push("origin", false).unwrap();
3814
    origin.refresh().unwrap();
3815
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
3816
    assert!(a.gc(true).is_ok());
3817
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
3818
3819
    // After a rotation the policy names only the new key, yet a fresh clone
3820
    // still takes the tags the old key made before it; the old key makes
3821
    // nothing new.
3822
    let rot = a.rotate_identity().unwrap();
3823
    let r = a.push("origin", false).unwrap();
3824
    origin.refresh().unwrap();
3825
    assert!(r.iter().all(|x| x.ok), "{r:?}");
3826
    let c = Repo::clone(&url, &root.join("c"))
3827
        .unwrap()
3828
        .with_home(root.join("home-c"));
3829
    assert_eq!(c.tag_heads("v3").unwrap(), Some(vec![h2]));
3830
    let (_, sp) = c.current_policy().unwrap().unwrap();
3831
    assert!(!sp.policy.authorizes(&key_a, "tags/v9"));
3832
    let made = c.identity(&rot.new).unwrap().created;
3833
    assert!(c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made - 1));
3834
    assert!(!c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made));
3835
    assert!(!c.predecessor_authorized(&sp.policy, &rot.new, "tags/v9", 0));
3836
}
3837
3838
#[test]
3839
fn multiple_workspaces_share_a_repository() {
3840
    hermetic();
3841
    let dir = tempfile::tempdir().unwrap();
3842
    let root = dir.path();
3843
    let main_dir = root.join("main");
3844
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
3845
    write(&main_dir, "a.txt", b"a\n");
3846
    let h1 = repo.commit("a", &[]).unwrap();
3847
    assert_eq!(repo.workspaces().unwrap().len(), 1);
3848
3849
    // A second workspace elsewhere, checked out on the bookmark.
3850
    let ws_dir = root.join("ws2");
3851
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
3852
    assert!(ws_dir.join(".oxy").is_file());
3853
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
3854
    assert_ne!(ws.workspace(), repo.workspace());
3855
    let list = repo.workspaces().unwrap();
3856
    assert_eq!(list.len(), 2);
3857
    assert!(list
3858
        .iter()
3859
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
3860
    assert!(!ws.snapshot("status").unwrap().changed);
3861
3862
    // Work in the second workspace: its own working copy, shared bookmark.
3863
    write(&ws_dir, "b.txt", b"b\n");
3864
    let s = ws.snapshot("status").unwrap();
3865
    assert_eq!(s.statuses.len(), 1);
3866
    assert!(
3867
        !repo.snapshot("status").unwrap().changed,
3868
        "the first workspace is untouched"
3869
    );
3870
    let h2 = ws.commit("b from ws2", &[]).unwrap();
3871
    repo.refresh().unwrap();
3872
    let mut heads = repo.bookmark_heads().unwrap();
3873
    heads.sort();
3874
    let mut want = vec![h1, h2];
3875
    want.sort();
3876
    assert_eq!(heads, want, "both workspaces see the bookmark move");
3877
    assert!(!main_dir.join("b.txt").exists());
3878
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
3879
        .unwrap();
3880
    assert!(main_dir.join("b.txt").exists());
3881
3882
    // Reopening from inside the second workspace finds the shared repository.
3883
    let reopened = Repo::open(&ws_dir).unwrap();
3884
    assert_eq!(reopened.workspace(), ws.workspace());
3885
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
3886
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
3887
3888
    // Workspaces cannot nest; forget drops one from the view but keeps files.
3889
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
3890
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
3891
    repo.workspace_forget(&ws.workspace()).unwrap();
3892
    assert_eq!(repo.workspaces().unwrap().len(), 1);
3893
    assert!(ws_dir.join("b.txt").exists());
3894
    assert!(
3895
        ws.snapshot("status").is_err(),
3896
        "a forgotten workspace is no longer in the view"
3897
    );
3898
3899
    // The working-copy lock: re-entrant in a thread; a lock whose process
3900
    // is gone is taken over, and a live process's is not, however old.
3901
    let lock = repo.lock_snapshot().unwrap();
3902
    let again = repo.lock_working_copy().unwrap();
3903
    drop(again);
3904
    drop(lock);
3905
    let lock_path = main_dir
3906
        .join(".oxy/workspaces")
3907
        .join(repo.workspace().to_hex())
3908
        .join("lock");
3909
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
3910
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
3911
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
3912
    age(&lock_path);
3913
    assert!(
3914
        !super::workspace::lock_is_stale(&lock_path),
3915
        "a live process keeps its lock"
3916
    );
3917
    fs::write(&lock_path, "4294967295").unwrap();
3918
    age(&lock_path);
3919
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
3920
}
3921
3922
#[test]
3923
fn attributes_binary_eol_nocompress_lockable() {
3924
    hermetic();
3925
    let dir = tempfile::tempdir().unwrap();
3926
    let root = dir.path();
3927
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3928
    write(
3929
        root,
3930
        ".oxyattributes",
3931
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
3932
    );
3933
    write(root, "plain.dat", b"no nul bytes here\n");
3934
    write(root, "notes.txt", b"one\r\ntwo\r\n");
3935
    write(root, "assets/model.bin", b"\0model");
3936
    let h = repo.commit("attrs", &[]).unwrap();
3937
    let snap = repo.load_state(&[h]).unwrap().materialize();
3938
    assert!(
3939
        snap.files["plain.dat"].mode.opaque,
3940
        "binary attribute forces opaque without NUL bytes"
3941
    );
3942
    assert!(
3943
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3944
        "stored with LF"
3945
    );
3946
    assert!(
3947
        !repo.snapshot("status").unwrap().changed,
3948
        "CRLF on disk equals LF in the state"
3949
    );
3950
    // nocompress chunks pack raw.
3951
    let r = repo.gc(true).unwrap();
3952
    assert!(r.packed.objects > 0);
3953
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
3954
    fs::remove_file(root.join("notes.txt")).unwrap();
3955
    repo.checkout(&[h], true, "co").unwrap();
3956
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
3957
    assert!(fs::metadata(root.join("assets/model.bin"))
3958
        .unwrap()
3959
        .permissions()
3960
        .readonly());
3961
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
3962
    repo.lock_path("assets/model.bin").unwrap();
3963
    assert!(!fs::metadata(root.join("assets/model.bin"))
3964
        .unwrap()
3965
        .permissions()
3966
        .readonly());
3967
    assert!(repo.is_locked("assets/model.bin"));
3968
    write(root, "assets/model.bin", b"\0model2");
3969
    repo.commit("edit model", &[]).unwrap();
3970
    repo.unlock_path("assets/model.bin").unwrap();
3971
    assert!(fs::metadata(root.join("assets/model.bin"))
3972
        .unwrap()
3973
        .permissions()
3974
        .readonly());
3975
    // A later checkout can still overwrite a read-only lockable file.
3976
    repo.checkout(&[h], true, "co").unwrap();
3977
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
3978
}
3979
3980
#[cfg(unix)]
3981
#[test]
3982
fn hooks_can_veto_observe_and_add_dependencies() {
3983
    use std::os::unix::fs::PermissionsExt;
3984
    hermetic();
3985
    let dir = tempfile::tempdir().unwrap();
3986
    let root = dir.path();
3987
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3988
    let hooks = root.join(".oxy/hooks");
3989
    fs::create_dir_all(&hooks).unwrap();
3990
    let hook = |name: &str, body: &str| {
3991
        let p = hooks.join(name);
3992
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
3993
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
3994
    };
3995
    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");
3996
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
3997
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
3998
    hook("pre-push", "echo pushing blocked >&2; exit 3");
3999
    write(root, ".oxyignore", b".last-*\n");
4000
    write(root, "a.txt", b"a\n");
4001
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
4002
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
4003
    let h1 = repo.commit("first", &[]).unwrap();
4004
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
4005
    assert!(
4006
        pre.contains("\"event\":\"pre-commit\"")
4007
            && pre.contains("\"path\":\"a.txt\"")
4008
            && pre.contains("\"message\":\"first\""),
4009
        "{pre}"
4010
    );
4011
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
4012
    assert!(post.contains(&h1.to_hex()), "{post}");
4013
    repo.checkout(&[h1], false, "co").unwrap();
4014
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
4015
        .unwrap()
4016
        .contains("post-checkout"));
4017
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
4018
    repo.save_config().unwrap();
4019
    let err = repo.push("origin", false).unwrap_err().to_string();
4020
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
4021
4022
    // semantic-deps: only when enabled; adds an explicit dependency.
4023
    write(root, "b.txt", b"b\n");
4024
    hook(
4025
        "semantic-deps",
4026
        &format!(
4027
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
4028
            h1.to_hex()
4029
        ),
4030
    );
4031
    let h2 = repo.commit("b without hook", &[]).unwrap();
4032
    assert!(
4033
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
4034
        "hook disabled by default"
4035
    );
4036
    repo.config.set("hooks.semantic-deps", "true").unwrap();
4037
    repo.save_config().unwrap();
4038
    write(root, "c.txt", b"c\n");
4039
    let h3 = repo.commit("c with hook", &[]).unwrap();
4040
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
4041
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
4042
    assert!(
4043
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
4044
        "{sem}"
4045
    );
4046
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
4047
}
4048
4049
#[test]
4050
fn amend_into_older_change_and_split() {
4051
    hermetic();
4052
    let dir = tempfile::tempdir().unwrap();
4053
    let root = dir.path();
4054
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
4055
    repo.create_identity("Ada", "a@b", IdentityScope::User)
4056
        .unwrap();
4057
    repo.set_user_config("core.sign", "change").unwrap();
4058
    write(root, "a.txt", b"one\ntwo\n");
4059
    let h0 = repo.commit("base", &[]).unwrap();
4060
    write(root, "a.txt", b"one\nTWO\n");
4061
    let h1 = repo.commit("edit two", &[]).unwrap();
4062
    write(root, "a.txt", b"one\nTWO\nthree\n");
4063
    let h2 = repo.commit("add three", &[]).unwrap();
4064
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
4065
4066
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
4067
    write(root, "a.txt", b"one\nTWO!\nthree\n");
4068
    let h1b = repo.amend_into(&h1, None).unwrap();
4069
    assert_ne!(h1b, h1);
4070
    let c1b = repo.store().get_change(&h1b).unwrap();
4071
    assert_eq!(c1b.change_id, id1);
4072
    assert_eq!(c1b.deps, vec![h0]);
4073
    assert!(matches!(
4074
        repo.verify_change(&h1b).unwrap(),
4075
        SignatureStatus::Valid { .. }
4076
    ));
4077
    let heads = repo.bookmark_heads().unwrap();
4078
    assert_eq!(heads.len(), 1);
4079
    let top = repo.store().get_change(&heads[0]).unwrap();
4080
    assert_eq!(top.message, "add three");
4081
    assert_eq!(
4082
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
4083
        [h0, h1b].into_iter().collect(),
4084
        "depends on the file's creator and the rewritten line"
4085
    );
4086
    let snap = repo.load_state(&heads).unwrap().materialize();
4087
    assert!(
4088
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
4089
    );
4090
    assert!(
4091
        !repo.snapshot("status").unwrap().changed,
4092
        "the working copy is clean after folding"
4093
    );
4094
    // Only h1b's own state shows the fix without "three".
4095
    let only = repo.load_state(&[h1b]).unwrap().materialize();
4096
    assert!(
4097
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
4098
    );
4099
    assert_eq!(repo.log().unwrap().len(), 4);
4100
4101
    // An edit to a line introduced by h2 cannot fold into h1.
4102
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
4103
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
4104
    assert!(err.contains("introduced after"), "{err}");
4105
    assert!(
4106
        repo.snapshot("status").unwrap().statuses.len() == 1,
4107
        "nothing was changed by the refusal"
4108
    );
4109
    write(root, "a.txt", b"one\nTWO!\nthree\n");
4110
4111
    // Split the head that touches two files.
4112
    write(root, "b.txt", b"b\n");
4113
    write(root, "c.txt", b"c\n");
4114
    let h3 = repo.commit("b and c", &[]).unwrap();
4115
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
4116
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
4117
    let c_1 = repo.store().get_change(&p1).unwrap();
4118
    let c_2 = repo.store().get_change(&p2).unwrap();
4119
    assert!(c_1.message.contains("part 1: b.txt"));
4120
    assert_eq!(c_2.change_id, id3);
4121
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
4122
    assert!(
4123
        heads.contains(&p1) && heads.contains(&p2),
4124
        "independent parts are both heads"
4125
    );
4126
    let snap = repo
4127
        .load_state(&repo.bookmark_heads().unwrap())
4128
        .unwrap()
4129
        .materialize();
4130
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
4131
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
4132
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
4133
    assert!(!repo.snapshot("status").unwrap().changed);
4134
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
4135
    let _ = h2;
4136
}
4137
4138
#[test]
4139
fn identity_lifecycle() {
4140
    hermetic();
4141
    let dir = tempfile::tempdir().unwrap();
4142
    let root = dir.path();
4143
    let origin = Repo::init(&root.join("origin")).unwrap();
4144
    let url = root.join("origin").to_string_lossy().to_string();
4145
    let mut a = Repo::clone(&url, &root.join("a"))
4146
        .unwrap()
4147
        .with_home(root.join("home-a"));
4148
    a.set_user_config("core.sign", "change").unwrap();
4149
    let (key_a, _) = a
4150
        .create_identity("Ada", "[email protected]", IdentityScope::User)
4151
        .unwrap();
4152
    write(&root.join("a"), "a.txt", b"a\n");
4153
    let h1 = a.commit("one", &[]).unwrap();
4154
    assert!(a.policy_init().unwrap().applied);
4155
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
4156
    origin.refresh().unwrap();
4157
4158
    // Expiry: an identity that had expired when the change was made does not authenticate it.
4159
    let mut e = Repo::init(&root.join("e"))
4160
        .unwrap()
4161
        .with_home(root.join("home-e"));
4162
    e.set_user_config("core.sign", "change").unwrap();
4163
    e.create_identity_with(
4164
        "Eve",
4165
        "[email protected]",
4166
        IdentityScope::User,
4167
        Some(Hlc::now().wall_ms - 1),
4168
    )
4169
    .unwrap();
4170
    write(&root.join("e"), "e.txt", b"e\n");
4171
    let he = e.commit("late", &[]).unwrap();
4172
    assert!(
4173
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
4174
    );
4175
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
4176
    let r = e
4177
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
4178
        .unwrap();
4179
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
4180
    write(&root.join("e"), "e.txt", b"e2\n");
4181
    let he2 = e.commit("in time", &[]).unwrap();
4182
    assert!(
4183
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
4184
    );
4185
4186
    // Rotation: a fresh key; the old change still verifies; the policy follows.
4187
    let r = a.rotate_identity().unwrap();
4188
    assert_eq!(r.old, key_a);
4189
    assert_eq!(a.config.author_key, Some(r.new));
4190
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
4191
    assert!(r.policy.as_ref().unwrap().applied);
4192
    let (_, sp) = a.current_policy().unwrap().unwrap();
4193
    assert_eq!(
4194
        (sp.policy.serial, sp.policy.roots.clone()),
4195
        (2, vec![r.new])
4196
    );
4197
    assert!(
4198
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
4199
        "superseded, not revoked"
4200
    );
4201
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
4202
    assert!(
4203
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
4204
    );
4205
    write(&root.join("a"), "a.txt", b"a2\n");
4206
    let h2 = a.commit("two", &[]).unwrap();
4207
    assert!(
4208
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
4209
    );
4210
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
4211
    let res = a.push("origin", false).unwrap();
4212
    origin.refresh().unwrap();
4213
    assert!(res.iter().all(|x| x.ok), "{res:?}");
4214
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
4215
    let key_a = r.new;
4216
4217
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
4218
    // identity object, so Ada's KeyId changes while her keys stay the same.
4219
    let mut b = Repo::clone(&url, &root.join("b"))
4220
        .unwrap()
4221
        .with_home(root.join("home-b"));
4222
    let (key_b, id_b) = b
4223
        .create_identity("Bob", "[email protected]", IdentityScope::User)
4224
        .unwrap();
4225
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
4226
    assert_eq!(r.old, key_a);
4227
    let key_a2 = r.new;
4228
    assert_eq!(
4229
        a.identity(&key_a2).unwrap().delegates,
4230
        vec![Delegate::full(key_b)]
4231
    );
4232
    assert_eq!(
4233
        a.identity(&key_a2).unwrap().ed25519_pk,
4234
        a.identity(&key_a).unwrap().ed25519_pk
4235
    );
4236
    assert!(
4237
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
4238
        "already a delegate"
4239
    );
4240
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
4241
    origin.refresh().unwrap();
4242
    write(&root.join("a"), "a.txt", b"a3\n");
4243
    let h3 = a.commit("three", &[]).unwrap();
4244
    assert!(
4245
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
4246
        "the same secret signs under the new KeyId"
4247
    );
4248
    // A change authored by Ada but signed only by Bob verifies through the delegation.
4249
    a.set_user_config("core.sign", "seal").unwrap();
4250
    write(&root.join("a"), "a.txt", b"a4\n");
4251
    let h4 = a.commit("four", &[]).unwrap();
4252
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
4253
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
4254
    a.store()
4255
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
4256
        .unwrap();
4257
    assert!(
4258
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
4259
    );
4260
    a.set_user_config("core.sign", "change").unwrap();
4261
    // Withdrawing the delegation re-issues the identity again.
4262
    let r = a.delegate_remove(&key_b).unwrap();
4263
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
4264
    assert!(a.delegate_remove(&key_b).is_err());
4265
    let key_a3 = r.new;
4266
    let res = a.push("origin", false).unwrap();
4267
    origin.refresh().unwrap();
4268
    assert!(res.iter().all(|x| x.ok), "{res:?}");
4269
4270
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
4271
    // both applied under the old threshold of 1. A grant then needs Bob too.
4272
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
4273
    assert!(a.policy_root_add(id_b.clone()).is_err());
4274
    assert!(a.policy_set_threshold(3).is_err());
4275
    assert!(a.policy_set_threshold(2).unwrap().applied);
4276
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
4277
    origin.refresh().unwrap();
4278
    b.pull("origin").unwrap();
4279
    assert_eq!(
4280
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
4281
        2
4282
    );
4283
    let mut c = Repo::init(&root.join("c"))
4284
        .unwrap()
4285
        .with_home(root.join("home-c"));
4286
    let (key_c, id_c) = c
4287
        .create_identity("Cy", "[email protected]", IdentityScope::User)
4288
        .unwrap();
4289
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
4290
    let proposal = a.policy_grant(id_c, None).unwrap();
4291
    assert!(!proposal.applied && proposal.sigs.len() == 1);
4292
    assert_eq!(proposal.policy.serial, serial_before + 1);
4293
    assert_eq!(
4294
        a.current_policy().unwrap().unwrap().1.policy.serial,
4295
        serial_before,
4296
        "a proposal changes nothing yet"
4297
    );
4298
    // Bob signs the proposal, handed over as a file, and it applies for him.
4299
    let bytes = proposal.signed().encode();
4300
    let signed = b
4301
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
4302
        .unwrap();
4303
    assert!(signed.applied && signed.sigs.len() == 2);
4304
    assert!(b
4305
        .current_policy()
4306
        .unwrap()
4307
        .unwrap()
4308
        .1
4309
        .policy
4310
        .authorizes(&key_c, "main"));
4311
    assert!(
4312
        b.policy_sign(signed.signed()).is_err(),
4313
        "a stale proposal is refused"
4314
    );
4315
    // Bob publishes it and Ada picks it up.
4316
    assert!(b
4317
        .push("origin", false)
4318
        .unwrap()
4319
        .iter()
4320
        .any(|x| x.name == "policy" && x.ok));
4321
    origin.refresh().unwrap();
4322
    a.pull("origin").unwrap();
4323
    assert_eq!(
4324
        a.current_policy().unwrap().unwrap().1.policy.serial,
4325
        serial_before + 1
4326
    );
4327
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
4328
    assert!(a.policy_revoke(&key_a3).is_err());
4329
    let u = a
4330
        .revoke_identity(&key_c, "left the project")
4331
        .unwrap()
4332
        .unwrap();
4333
    assert!(!u.applied);
4334
    assert!(a.is_revoked(&key_c).unwrap());
4335
    assert!(!b.is_revoked(&key_c).unwrap());
4336
    let u = b.policy_sign(u.signed()).unwrap();
4337
    assert!(u.applied && u.policy.is_revoked(&key_c));
4338
    assert!(b.is_revoked(&key_c).unwrap());
4339
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
4340
    assert!(
4341
        b.policy_revoke(&key_a3).is_err(),
4342
        "would leave one root for a threshold of 2"
4343
    );
4344
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
4345
    let key_c_own = c.config.author_key.unwrap();
4346
    assert!(c
4347
        .revoke_identity(&key_c_own, "lost laptop")
4348
        .unwrap()
4349
        .is_none());
4350
    assert!(c.is_revoked(&key_c_own).unwrap());
4351
    assert_eq!(key_c_own, key_c);
4352
}
4353
4354
#[test]
4355
fn renames_are_detected_and_tracked_as_moves() {
4356
    hermetic();
4357
    let dir = tempfile::tempdir().unwrap();
4358
    let root = dir.path();
4359
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4360
    write(
4361
        root,
4362
        "src/old.rs",
4363
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
4364
    );
4365
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
4366
    write(root, "tiny.txt", b"x\n");
4367
    let h1 = repo.commit("base", &[]).unwrap();
4368
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
4369
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
4370
4371
    // Rename with a small edit, a binary moved unchanged, and a rewrite
4372
    // that shares nothing with the removed file.
4373
    fs::remove_file(root.join("src/old.rs")).unwrap();
4374
    write(
4375
        root,
4376
        "lib/new.rs",
4377
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
4378
    );
4379
    fs::remove_file(root.join("img.bin")).unwrap();
4380
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
4381
    fs::remove_file(root.join("tiny.txt")).unwrap();
4382
    write(root, "other.txt", b"completely different\n");
4383
    let snap = repo.snapshot("status").unwrap();
4384
    let statuses: Vec<(&str, ChangeStatus)> = snap
4385
        .statuses
4386
        .iter()
4387
        .map(|s| (s.path.as_str(), s.status))
4388
        .collect();
4389
    assert_eq!(
4390
        statuses,
4391
        vec![
4392
            ("assets/img.bin", ChangeStatus::Renamed),
4393
            ("lib/new.rs", ChangeStatus::Renamed),
4394
            ("other.txt", ChangeStatus::Added),
4395
            ("src", ChangeStatus::Removed),
4396
            ("tiny.txt", ChangeStatus::Removed)
4397
        ]
4398
    );
4399
    let h2 = repo.commit("move things", &[]).unwrap();
4400
    let c = repo.store().get_change(&h2).unwrap();
4401
    let moves: Vec<_> = c
4402
        .tree_ops
4403
        .iter()
4404
        .filter(|op| matches!(op, TreeOp::Move { .. }))
4405
        .collect();
4406
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
4407
    assert!(c.tree_ops.iter().any(
4408
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
4409
    ));
4410
    assert!(c.tree_ops.iter().any(
4411
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
4412
    ));
4413
    let snap = repo.load_state(&[h2]).unwrap().materialize();
4414
    assert_eq!(
4415
        snap.files["lib/new.rs"].node, node_old,
4416
        "the node survives the rename"
4417
    );
4418
    assert!(
4419
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
4420
    );
4421
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
4422
    assert!(render_change(
4423
        &c,
4424
        &repo.load_state(&[h1]).unwrap(),
4425
        &repo.load_state(&[h1]).unwrap().materialize()
4426
    )
4427
    .contains("R src/old.rs -> lib/new.rs"));
4428
    // A fresh checkout reproduces the tree.
4429
    let other = tempfile::tempdir().unwrap();
4430
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
4431
    assert_eq!(
4432
        fs::read(other.path().join("lib/new.rs")).unwrap(),
4433
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
4434
    );
4435
    assert!(!other.path().join("src").exists());
4436
    assert!(!clone.snapshot("status").unwrap().changed);
4437
    // Similarity is line based, byte weighted.
4438
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
4439
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
4440
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
4441
    assert_eq!(similarity(b"", b"x\n"), 0);
4442
}
4443
4444
#[test]
4445
fn git_fetch_and_push_round_trip() {
4446
    hermetic();
4447
    if std::process::Command::new("git")
4448
        .arg("--version")
4449
        .output()
4450
        .is_err()
4451
    {
4452
        eprintln!("git not installed; skipping");
4453
        return;
4454
    }
4455
    let dir = tempfile::tempdir().unwrap();
4456
    let root = dir.path();
4457
    let git_in = |d: &Path, args: &[&str]| -> String {
4458
        let out = std::process::Command::new("git")
4459
            .arg("-C")
4460
            .arg(d)
4461
            .args([
4462
                "-c",
4463
                "user.name=Grace",
4464
                "-c",
4465
                "[email protected]",
4466
                "-c",
4467
                "commit.gpgsign=false",
4468
            ])
4469
            .args(args)
4470
            .output()
4471
            .unwrap();
4472
        assert!(
4473
            out.status.success(),
4474
            "git {args:?}: {}",
4475
            String::from_utf8_lossy(&out.stderr)
4476
        );
4477
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4478
    };
4479
    // A bare "remote" and a work tree that pushes to it.
4480
    let remote = root.join("remote.git");
4481
    fs::create_dir_all(&remote).unwrap();
4482
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
4483
    let work = root.join("work");
4484
    git_in(
4485
        root,
4486
        &[
4487
            "clone",
4488
            "-q",
4489
            remote.to_str().unwrap(),
4490
            work.to_str().unwrap(),
4491
        ],
4492
    );
4493
    git_in(&work, &["checkout", "-q", "-b", "main"]);
4494
    write(&work, "README.md", b"# Project\n");
4495
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
4496
    git_in(&work, &["add", "."]);
4497
    git_in(&work, &["commit", "-q", "-m", "initial"]);
4498
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
4499
    git_in(&work, &["commit", "-q", "-am", "second"]);
4500
    git_in(&work, &["push", "-q", "origin", "main"]);
4501
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
4502
4503
    // Fetch into a fresh oxy repository.
4504
    let o = root.join("oxy");
4505
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
4506
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
4507
        .unwrap();
4508
    let url = remote.to_string_lossy().to_string();
4509
    let r = repo.git_fetch(&url, "main").unwrap();
4510
    assert_eq!((r.commits, r.heads), (2, 1));
4511
    assert_eq!(
4512
        fs::read(o.join("src/lib.rs")).unwrap(),
4513
        b"pub fn a() {}\npub fn b() {}\n"
4514
    );
4515
    assert!(!repo.snapshot("status").unwrap().changed);
4516
    assert_eq!(
4517
        repo.git_fetch(&url, "main").unwrap().commits,
4518
        0,
4519
        "nothing new"
4520
    );
4521
4522
    // An oxy change, pushed back: one commit on top of the Git tip.
4523
    write(
4524
        &o,
4525
        "src/lib.rs",
4526
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
4527
    );
4528
    write(&o, "NOTES.md", b"from oxy\n");
4529
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
4530
    let r = repo.git_push(&url, "main").unwrap();
4531
    assert_eq!(r.exported, 1, "{r:?}");
4532
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
4533
    assert_eq!(
4534
        git_in(&work, &["log", "--format=%s", "main"]),
4535
        "add c and notes\nsecond\ninitial"
4536
    );
4537
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
4538
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
4539
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
4540
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
4541
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
4542
    assert_eq!(
4543
        repo.git_push(&url, "main").unwrap().exported,
4544
        0,
4545
        "already pushed"
4546
    );
4547
4548
    // Git moves on; pushing without fetching is refused, fetching brings
4549
    // the commit in and the working copy follows.
4550
    write(&work, "README.md", b"# Project\n\nMore.\n");
4551
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
4552
    git_in(&work, &["push", "-q", "origin", "main"]);
4553
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
4554
    assert!(repo
4555
        .git_push(&url, "main")
4556
        .unwrap_err()
4557
        .to_string()
4558
        .contains("fetch"));
4559
    let r = repo.git_fetch(&url, "main").unwrap();
4560
    assert_eq!(
4561
        (r.commits, r.heads),
4562
        (1, 2),
4563
        "the Git change and the oxy change commute"
4564
    );
4565
    assert_eq!(
4566
        fs::read(o.join("README.md")).unwrap(),
4567
        b"# Project\n\nMore.\n"
4568
    );
4569
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
4570
    assert!(!repo.snapshot("status").unwrap().changed);
4571
    // Another oxy change pushes on top of Git's newest commit.
4572
    write(&o, "NOTES.md", b"from oxy\nagain\n");
4573
    repo.commit("notes again", &[]).unwrap();
4574
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
4575
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
4576
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
4577
    assert_eq!(
4578
        fs::read(work.join("NOTES.md")).unwrap(),
4579
        b"from oxy\nagain\n"
4580
    );
4581
    assert_eq!(
4582
        git_in(&work, &["log", "--format=%s", "main"])
4583
            .lines()
4584
            .count(),
4585
        5
4586
    );
4587
}
4588
4589
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
4590
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
4591
#[test]
4592
#[ignore]
4593
fn bench_one_gibibyte_file() {
4594
    hermetic();
4595
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
4596
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
4597
        Some(d) => tempfile::tempdir_in(d).unwrap(),
4598
        None => tempfile::tempdir().unwrap(),
4599
    };
4600
    let root = dir.path();
4601
    let repo = Repo::init(&root.join("r"))
4602
        .unwrap()
4603
        .with_home(root.join("home"));
4604
    let size = 1usize << 30;
4605
    let mut data = vec![0u8; size];
4606
    let mut x = 0x9e3779b97f4a7c15u64;
4607
    for chunk in data.chunks_mut(8) {
4608
        x ^= x << 13;
4609
        x ^= x >> 7;
4610
        x ^= x << 17;
4611
        let b = x.to_le_bytes();
4612
        chunk.copy_from_slice(&b[..chunk.len()]);
4613
    }
4614
    let t = std::time::Instant::now();
4615
    write(&root.join("r"), "big.bin", &data);
4616
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
4617
    let t = std::time::Instant::now();
4618
    let h = repo.commit("big", &[]).unwrap();
4619
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
4620
    let t = std::time::Instant::now();
4621
    assert!(!repo.snapshot("status").unwrap().changed);
4622
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
4623
    let t = std::time::Instant::now();
4624
    let objects = repo.store().list().unwrap().len();
4625
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
4626
    let t = std::time::Instant::now();
4627
    let g = repo.gc(true).unwrap();
4628
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
4629
    let t = std::time::Instant::now();
4630
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
4631
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
4632
    let t = std::time::Instant::now();
4633
    let back = fs::read(root.join("c/big.bin")).unwrap();
4634
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
4635
    eprintln!("read back and verify: {:.2?}", t.elapsed());
4636
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
4637
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
4638
    eprintln!(
4639
        "store size: {:.1} MiB for 1 GiB of data",
4640
        store_bytes as f64 / (1024.0 * 1024.0)
4641
    );
4642
}
4643
4644
fn walkdir_size(p: &Path) -> u64 {
4645
    let mut total = 0;
4646
    if let Ok(rd) = fs::read_dir(p) {
4647
        for e in rd.flatten() {
4648
            let path = e.path();
4649
            if path.is_dir() {
4650
                total += walkdir_size(&path);
4651
            } else if let Ok(m) = fs::metadata(&path) {
4652
                total += m.len();
4653
            }
4654
        }
4655
    }
4656
    total
4657
}
4658
4659
/// An opaque file whose size and mtime match the manifest is not read on
4660
/// the next snapshot: its blob comes from the manifest's stat cache.
4661
#[cfg(unix)]
4662
#[test]
4663
fn stat_cache_skips_reading_unchanged_opaque_files() {
4664
    use std::os::unix::fs::PermissionsExt;
4665
    hermetic();
4666
    let dir = tempfile::tempdir().unwrap();
4667
    let root = dir.path();
4668
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4669
    let mut big = vec![0u8; 300 * 1024];
4670
    for (i, b) in big.iter_mut().enumerate() {
4671
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
4672
    }
4673
    big[0] = 0;
4674
    write(root, "big.bin", &big);
4675
    write(root, "a.txt", b"text\n");
4676
    let h1 = repo.commit("base", &[]).unwrap();
4677
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4678
    assert!(
4679
        m.entries["big.bin"].blob.is_some(),
4680
        "opaque files record their blob"
4681
    );
4682
    assert!(m.entries["a.txt"].blob.is_none());
4683
    let blob = m.entries["big.bin"].blob.unwrap();
4684
    assert!(repo.store().has(&blob));
4685
4686
    // Files modified within two seconds of the manifest are racy and still
4687
    // read; age the file so the cache applies, then snapshot to record it.
4688
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4689
    fs::File::options()
4690
        .write(true)
4691
        .open(root.join("big.bin"))
4692
        .unwrap()
4693
        .set_modified(old)
4694
        .unwrap();
4695
    assert!(!repo.snapshot("status").unwrap().changed);
4696
    // Now the file cannot be read at all; the snapshot succeeds without it.
4697
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
4698
    let snap = repo.snapshot("status").unwrap();
4699
    assert!(
4700
        !snap.changed && snap.statuses.is_empty(),
4701
        "{:?}",
4702
        snap.statuses
4703
    );
4704
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
4705
    // A real change (new mtime, new content) is seen and committed correctly.
4706
    let mut big2 = big.clone();
4707
    big2[10] ^= 0xff;
4708
    write(root, "big.bin", &big2);
4709
    let snap = repo.snapshot("status").unwrap();
4710
    assert_eq!(
4711
        snap.statuses
4712
            .iter()
4713
            .map(|s| (s.path.as_str(), s.status))
4714
            .collect::<Vec<_>>(),
4715
        vec![("big.bin", ChangeStatus::Modified)]
4716
    );
4717
    let h2 = repo.commit("edit", &[]).unwrap();
4718
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
4719
    assert_eq!(
4720
        files["big.bin"].content,
4721
        FileContent::Opaque {
4722
            blobs: vec![Repo::blob_ref(&big2)]
4723
        }
4724
    );
4725
    // Checkout writes a manifest with blobs too, so the next status is cached.
4726
    repo.checkout(&[h1], false, "checkout").unwrap();
4727
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4728
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
4729
    assert!(!repo.snapshot("status").unwrap().changed);
4730
}
4731
4732
#[test]
4733
fn status_json_lists_conflicts_with_contributors() {
4734
    hermetic();
4735
    let dir = tempfile::tempdir().unwrap();
4736
    let root = dir.path();
4737
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4738
    write(root, "a.txt", b"one\n");
4739
    let h1 = repo.commit("base", &[]).unwrap();
4740
    write(root, "a.txt", b"one\nleft\n");
4741
    let ha = repo.commit("left", &[]).unwrap();
4742
    repo.checkout(&[h1], true, "checkout").unwrap();
4743
    write(root, "a.txt", b"one\nright\n");
4744
    let hb = repo.commit("right", &[]).unwrap();
4745
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
4746
    let snap = repo.snapshot("status").unwrap();
4747
    assert!(snap.base_snapshot.is_conflicted());
4748
    let json = repo.status_json(&snap).unwrap();
4749
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
4750
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
4751
    assert!(json.contains("\"conflicted\":true"), "{json}");
4752
    assert!(
4753
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
4754
        "{json}"
4755
    );
4756
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
4757
    assert!(json.contains("\"resolved\":false"), "{json}");
4758
    assert!(json.starts_with('{') && json.ends_with('}'));
4759
    // Resolve and the report says so; a clean copy has no conflicts.
4760
    write(root, "a.txt", b"one\nleft\nright\n");
4761
    let snap = repo.snapshot("status").unwrap();
4762
    let json = repo.status_json(&snap).unwrap();
4763
    assert!(json.contains("\"resolved\":true"), "{json}");
4764
    repo.commit("resolve", &[]).unwrap();
4765
    let snap = repo.snapshot("status").unwrap();
4766
    let json = repo.status_json(&snap).unwrap();
4767
    assert!(
4768
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
4769
        "{json}"
4770
    );
4771
}
4772
4773
#[test]
4774
fn ignore_rules_do_not_untrack_files() {
4775
    hermetic();
4776
    let dir = tempfile::tempdir().unwrap();
4777
    let root = dir.path();
4778
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4779
    write(root, "src.c", b"int x;\n");
4780
    write(root, "build/out.o", b"\0obj");
4781
    write(root, "sub/keep.log", b"keep\n");
4782
    write(root, "sub/junk.log", b"junk\n");
4783
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
4784
    let snap = repo.snapshot("status").unwrap();
4785
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
4786
    assert_eq!(
4787
        added,
4788
        vec![".oxyignore", "src.c", "sub/keep.log"],
4789
        "anchored, glob, and negated rules"
4790
    );
4791
    let h1 = repo.commit("base", &[]).unwrap();
4792
    // Ignoring a tracked file changes nothing about it.
4793
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
4794
    let snap = repo.snapshot("status").unwrap();
4795
    assert_eq!(
4796
        snap.statuses
4797
            .iter()
4798
            .map(|s| s.path.as_str())
4799
            .collect::<Vec<_>>(),
4800
        vec![".oxyignore"]
4801
    );
4802
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
4803
    assert!(repo
4804
        .load_state(&[h2])
4805
        .unwrap()
4806
        .materialize()
4807
        .files
4808
        .contains_key("src.c"));
4809
    // Its edits are still seen, by status and by the prompt.
4810
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
4811
    write(root, "src.c", b"int x, y;\n");
4812
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
4813
    let snap = repo.snapshot("status").unwrap();
4814
    assert_eq!(
4815
        snap.statuses
4816
            .iter()
4817
            .map(|s| (s.path.as_str(), s.status))
4818
            .collect::<Vec<_>>(),
4819
        vec![("src.c", ChangeStatus::Modified)]
4820
    );
4821
    let h3 = repo.commit("edit src.c", &[]).unwrap();
4822
    assert!(
4823
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
4824
    );
4825
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
4826
    fs::remove_file(root.join("src.c")).unwrap();
4827
    let snap = repo.snapshot("status").unwrap();
4828
    assert_eq!(
4829
        snap.statuses
4830
            .iter()
4831
            .map(|s| (s.path.as_str(), s.status))
4832
            .collect::<Vec<_>>(),
4833
        vec![("src.c", ChangeStatus::Removed)]
4834
    );
4835
    repo.checkout(&[h3], true, "checkout").unwrap();
4836
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
4837
    assert!(!repo.snapshot("status").unwrap().changed);
4838
    let _ = h1;
4839
}
4840
4841
#[test]
4842
fn split_works_on_non_heads_by_node() {
4843
    hermetic();
4844
    let dir = tempfile::tempdir().unwrap();
4845
    let root = dir.path();
4846
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4847
    write(root, "a.txt", b"one\n");
4848
    write(root, "junk/x.lock", b"lock\n");
4849
    let h1 = repo.commit("work plus junk", &[]).unwrap();
4850
    write(root, "a.txt", b"one\ntwo\n");
4851
    let h2 = repo.commit("more work", &[]).unwrap();
4852
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
4853
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
4854
    // h1 is not a head: split it by node.
4855
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
4856
    assert_ne!(h1b, h1);
4857
    assert_eq!(
4858
        repo.store().get_change(&h1b).unwrap().change_id,
4859
        id1,
4860
        "the rest keeps the ChangeId"
4861
    );
4862
    let junk = repo.store().get_change(&hj).unwrap();
4863
    assert!(junk.tree_ops.iter().all(
4864
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
4865
    ));
4866
    let heads = repo.bookmark_heads().unwrap();
4867
    assert!(
4868
        heads.contains(&hj),
4869
        "the split-off part is a head of its own"
4870
    );
4871
    let snap = repo.load_state(&heads).unwrap().materialize();
4872
    assert!(
4873
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
4874
        "the dependent was rewritten onto the new hash"
4875
    );
4876
    assert!(snap.files.contains_key("junk/x.lock"));
4877
    let h2b = heads
4878
        .iter()
4879
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
4880
        .copied()
4881
        .unwrap();
4882
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
4883
    assert!(!repo.snapshot("status").unwrap().changed);
4884
    // Abandoning the split-off head removes the junk from history.
4885
    repo.abandon(&hj).unwrap();
4886
    let heads = repo.bookmark_heads().unwrap();
4887
    let snap = repo.load_state(&heads).unwrap().materialize();
4888
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
4889
    assert!(snap.files.contains_key("a.txt"));
4890
    // A dependent that touches the split-off paths blocks the split.
4891
    write(root, "junk/y.lock", b"y\n");
4892
    let hb = repo.commit("junk base", &[]).unwrap();
4893
    write(root, "junk/y.lock", b"yy\n");
4894
    write(root, "b.txt", b"b\n");
4895
    repo.commit("touches junk", &[]).unwrap();
4896
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
4897
    assert!(err.contains("depends on the split-off paths"), "{err}");
4898
}
4899
4900
#[test]
4901
fn bookmarks_switch_merge_and_push() {
4902
    hermetic();
4903
    let dir = tempfile::tempdir().unwrap();
4904
    let root = dir.path();
4905
    let origin = Repo::init(&root.join("origin")).unwrap();
4906
    let url = root.join("origin").to_string_lossy().to_string();
4907
    let mut repo = Repo::clone(&url, &root.join("r"))
4908
        .unwrap()
4909
        .with_home(root.join("home"));
4910
    let r = root.join("r");
4911
    write(&r, "a.txt", b"a\n");
4912
    let h_a = repo.commit("a", &[]).unwrap();
4913
    assert!(repo.push("origin", false).unwrap()[0].ok);
4914
    origin.refresh().unwrap();
4915
4916
    // A bookmark at the working copy's base, then work on it.
4917
    assert!(repo.bookmark_create("bad name..", None).is_err());
4918
    assert!(repo.bookmark_create("-x", None).is_err());
4919
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
4920
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
4921
    repo.bookmark_switch("feature", false).unwrap();
4922
    assert_eq!(repo.config.bookmark, "feature");
4923
    write(&r, "a.txt", b"a\nb\n");
4924
    write(&r, "b.txt", b"b\n");
4925
    let h_b = repo.commit("b on feature", &[]).unwrap();
4926
    assert_eq!(
4927
        repo.bookmark_heads().unwrap(),
4928
        vec![h_b],
4929
        "b edits a.txt, so it depends on a"
4930
    );
4931
    assert_eq!(
4932
        repo.resolve_heads("main").unwrap(),
4933
        vec![h_a],
4934
        "main is untouched"
4935
    );
4936
    assert_eq!(
4937
        repo.resolve_change("feature").unwrap(),
4938
        h_b,
4939
        "a one-head bookmark names its change"
4940
    );
4941
    // Reopening keeps the workspace's bookmark.
4942
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
4943
    assert_eq!(reopened.config.bookmark, "feature");
4944
    // Back to main: b.txt goes away; work there.
4945
    repo.bookmark_switch("main", false).unwrap();
4946
    assert!(!r.join("b.txt").exists());
4947
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
4948
    write(&r, "c.txt", b"c\n");
4949
    let h_c = repo.commit("c on main", &[]).unwrap();
4950
    let list = repo.bookmarks().unwrap();
4951
    assert_eq!(
4952
        list.iter()
4953
            .map(|b| (b.name.as_str(), b.current))
4954
            .collect::<Vec<_>>(),
4955
        vec![("feature", false), ("main", true)]
4956
    );
4957
    assert_eq!(
4958
        list.iter().find(|b| b.name == "main").unwrap().ahead,
4959
        Some(1),
4960
        "c is not on origin yet"
4961
    );
4962
    // Merge feature into main: the union, both heads, no merge change.
4963
    let m = repo.merge("feature").unwrap();
4964
    assert!(m.changed && m.checked_out);
4965
    let mut want = vec![h_b, h_c];
4966
    want.sort();
4967
    assert_eq!(m.heads, want);
4968
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
4969
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
4970
    assert!(repo.merge("main").is_err());
4971
    // The other bookmark can be pushed by name and appears at origin.
4972
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
4973
    origin.refresh().unwrap();
4974
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
4975
    assert!(repo.push("origin", false).unwrap()[0].ok);
4976
    origin.refresh().unwrap();
4977
    assert_eq!(
4978
        repo.bookmarks()
4979
            .unwrap()
4980
            .iter()
4981
            .find(|b| b.name == "main")
4982
            .unwrap()
4983
            .ahead,
4984
        Some(0)
4985
    );
4986
    // A second workspace inherits the current bookmark and can switch independently.
4987
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
4988
    assert_eq!(ws.config.bookmark, "main");
4989
    let mut ws = ws;
4990
    ws.bookmark_switch("feature", false).unwrap();
4991
    assert_eq!(
4992
        Repo::open(&r).unwrap().config.bookmark,
4993
        "main",
4994
        "the first workspace is unaffected"
4995
    );
4996
    assert!(
4997
        repo.bookmark_delete("feature").is_err(),
4998
        "current bookmark of another workspace"
4999
    );
5000
    ws.bookmark_switch("main", false).unwrap();
5001
    // Set and delete.
5002
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
5003
    assert!(repo.bookmark_delete("main").is_err(), "current here");
5004
    repo.bookmark_delete("feature").unwrap();
5005
    assert!(repo.resolve_heads("feature").is_err());
5006
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
5007
    assert!(
5008
        repo.checkout(&[h_a], false, "checkout").is_ok(),
5009
        "changes of a deleted bookmark remain"
5010
    );
5011
}
5012
5013
#[test]
5014
fn oxygen_subrepos_pin_follow_and_update() {
5015
    hermetic();
5016
    let dir = tempfile::tempdir().unwrap();
5017
    let root = dir.path();
5018
    // A library repository with two commits, and a bare-ish origin for it.
5019
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
5020
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
5021
    let lib = Repo::clone(&lib_url, &root.join("lib"))
5022
        .unwrap()
5023
        .with_home(root.join("home"));
5024
    write(&root.join("lib"), "lib.txt", b"v1\n");
5025
    let l1 = lib.commit("lib v1", &[]).unwrap();
5026
    assert!(lib.push("origin", false).unwrap()[0].ok);
5027
    let _ = lib_origin;
5028
5029
    // The application (a clone of its own origin) adds it as a subrepo.
5030
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
5031
    let app_url = root.join("app-origin").to_string_lossy().to_string();
5032
    let _ = app_origin;
5033
    let app_dir = root.join("app");
5034
    let app = Repo::clone(&app_url, &app_dir)
5035
        .unwrap()
5036
        .with_home(root.join("home"));
5037
    write(&app_dir, "main.txt", b"app\n");
5038
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
5039
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
5040
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
5041
    let snap = app.snapshot("status").unwrap();
5042
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
5043
    assert_eq!(
5044
        paths,
5045
        vec![".oxymodules", "libs/lib", "main.txt"],
5046
        "the nested files are not walked"
5047
    );
5048
    let a1 = app.commit("app with lib", &[]).unwrap();
5049
    let files = app.load_state(&[a1]).unwrap().materialize().files;
5050
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
5051
    assert!(!files.contains_key("libs/lib/lib.txt"));
5052
    assert!(!app.snapshot("status").unwrap().changed);
5053
    let subs = app.subrepos().unwrap();
5054
    assert_eq!(subs.len(), 1);
5055
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
5056
5057
    // Advance the nested repository: the parent sees a modified pin.
5058
    let nested = Repo::open(&app_dir.join("libs/lib"))
5059
        .unwrap()
5060
        .with_home(root.join("home"));
5061
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
5062
    let l2 = nested.commit("lib v2", &[]).unwrap();
5063
    assert!(nested.push("origin", false).unwrap()[0].ok);
5064
    let snap = app.snapshot("status").unwrap();
5065
    assert_eq!(
5066
        snap.statuses
5067
            .iter()
5068
            .map(|s| (s.path.as_str(), s.status))
5069
            .collect::<Vec<_>>(),
5070
        vec![("libs/lib", ChangeStatus::Modified)]
5071
    );
5072
    let a2 = app.commit("bump lib", &[]).unwrap();
5073
    // Checking out the older app state brings the nested working copy back
5074
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
5075
    let r = app.checkout(&[a1], false, "checkout").unwrap();
5076
    assert!(
5077
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
5078
        "{:?}",
5079
        r.notes
5080
    );
5081
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
5082
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
5083
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
5084
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
5085
    assert!(!app.snapshot("status").unwrap().changed);
5086
    // A dirty nested repository is left alone and reported.
5087
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
5088
    let r = app.checkout(&[a2], false, "checkout").unwrap();
5089
    assert!(
5090
        r.notes.iter().any(|n| n.contains("uncommitted")),
5091
        "{:?}",
5092
        r.notes
5093
    );
5094
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
5095
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
5096
    let r = app.submodule_update(false, &[]).unwrap();
5097
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
5098
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
5099
    let _ = l2;
5100
5101
    // A fresh clone of the app has the pin but no nested repository until update --init.
5102
    assert!(app.push("origin", false).unwrap()[0].ok);
5103
    let clone_dir = root.join("app-clone");
5104
    let clone = Repo::clone(&app_url, &clone_dir)
5105
        .unwrap()
5106
        .with_home(root.join("home"));
5107
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
5108
    assert_eq!(
5109
        clone.submodule_update(false, &[]).unwrap(),
5110
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
5111
    );
5112
    assert_eq!(
5113
        clone.submodule_update(true, &[]).unwrap(),
5114
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
5115
    );
5116
    assert_eq!(
5117
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
5118
        b"v2\n"
5119
    );
5120
    assert!(!clone.snapshot("status").unwrap().changed);
5121
    // Removing the subrepo leaves the directory and drops the node.
5122
    clone.submodule_remove("libs/lib").unwrap();
5123
    let snap = clone.snapshot("status").unwrap();
5124
    assert!(
5125
        snap.statuses
5126
            .iter()
5127
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
5128
        "{:?}",
5129
        snap.statuses
5130
    );
5131
    let c = clone.commit("drop lib", &[]).unwrap();
5132
    assert!(!clone
5133
        .load_state(&[c])
5134
        .unwrap()
5135
        .materialize()
5136
        .files
5137
        .contains_key("libs/lib"));
5138
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
5139
    assert!(
5140
        !clone.snapshot("status").unwrap().changed,
5141
        "an unregistered nested repository is ignored"
5142
    );
5143
}
5144
5145
#[test]
5146
fn git_submodules_import_and_export_as_gitlinks() {
5147
    hermetic();
5148
    if std::process::Command::new("git")
5149
        .arg("--version")
5150
        .output()
5151
        .is_err()
5152
    {
5153
        eprintln!("git not installed; skipping");
5154
        return;
5155
    }
5156
    let dir = tempfile::tempdir().unwrap();
5157
    let root = dir.path();
5158
    let git_in = |d: &Path, args: &[&str]| -> String {
5159
        let out = std::process::Command::new("git")
5160
            .arg("-C")
5161
            .arg(d)
5162
            .args([
5163
                "-c",
5164
                "user.name=Grace",
5165
                "-c",
5166
                "[email protected]",
5167
                "-c",
5168
                "commit.gpgsign=false",
5169
                "-c",
5170
                "protocol.file.allow=always",
5171
            ])
5172
            .args(args)
5173
            .output()
5174
            .unwrap();
5175
        assert!(
5176
            out.status.success(),
5177
            "git {args:?}: {}",
5178
            String::from_utf8_lossy(&out.stderr)
5179
        );
5180
        String::from_utf8_lossy(&out.stdout).trim().to_string()
5181
    };
5182
    let sub = root.join("sub");
5183
    fs::create_dir_all(&sub).unwrap();
5184
    git_in(&sub, &["init", "-q", "-b", "main"]);
5185
    write(&sub, "s.txt", b"sub\n");
5186
    git_in(&sub, &["add", "."]);
5187
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
5188
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
5189
    let g = root.join("main.git");
5190
    fs::create_dir_all(&g).unwrap();
5191
    git_in(&g, &["init", "-q", "-b", "main"]);
5192
    write(&g, "README.md", b"# app\n");
5193
    git_in(&g, &["add", "."]);
5194
    git_in(&g, &["commit", "-q", "-m", "initial"]);
5195
    git_in(
5196
        &g,
5197
        &[
5198
            "submodule",
5199
            "add",
5200
            "-q",
5201
            sub.to_str().unwrap(),
5202
            "vendor/sub",
5203
        ],
5204
    );
5205
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
5206
5207
    let dest = root.join("oxy");
5208
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
5209
    let rep = repo.import_git(&g, "main").unwrap();
5210
    assert_eq!((rep.commits, rep.submodules), (2, 1));
5211
    let files = repo
5212
        .load_state(&repo.bookmark_heads().unwrap())
5213
        .unwrap()
5214
        .materialize()
5215
        .files;
5216
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
5217
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
5218
        panic!()
5219
    };
5220
    assert_eq!(
5221
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
5222
        crate::subrepo::Pin::Git {
5223
            sha: sub_sha.clone(),
5224
            branch: "HEAD".into()
5225
        }
5226
    );
5227
    let modules =
5228
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
5229
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
5230
    assert!(modules.entries["vendor/sub"].git);
5231
    assert!(
5232
        files.contains_key(".gitmodules"),
5233
        "the Git file is kept for round trips"
5234
    );
5235
    assert!(
5236
        !dest.join("vendor/sub/.git").exists(),
5237
        "not cloned until update --init"
5238
    );
5239
    assert!(!repo.snapshot("status").unwrap().changed);
5240
    // update --init clones it at the pinned commit; status is unchanged.
5241
    assert_eq!(
5242
        repo.submodule_update(true, &[]).unwrap(),
5243
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
5244
    );
5245
    assert_eq!(
5246
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
5247
        sub_sha
5248
    );
5249
    assert!(!repo.snapshot("status").unwrap().changed);
5250
    // Export writes the gitlink and .gitmodules back.
5251
    let mirror = root.join("mirror.git");
5252
    let rep = repo.git_export(&mirror).unwrap();
5253
    assert_eq!(rep.skipped_subrepos, 0);
5254
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
5255
    assert!(
5256
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
5257
        "{ls}"
5258
    );
5259
    assert_eq!(
5260
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
5261
        ".gitmodules\nREADME.md\nvendor"
5262
    );
5263
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
5264
    assert_eq!(
5265
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
5266
        orig_tree,
5267
        "tree round trip"
5268
    );
5269
}
5270
5271
#[test]
5272
fn partial_commits_by_path_and_by_hunk() {
5273
    hermetic();
5274
    let dir = tempfile::tempdir().unwrap();
5275
    let root = dir.path();
5276
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5277
    write(root, "a.txt", b"1\n2\n3\n");
5278
    write(root, "b.txt", b"b\n");
5279
    let h0 = repo.commit("base", &[]).unwrap();
5280
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
5281
    write(root, "b.txt", b"b\nbb\n");
5282
    write(root, "c.txt", b"c\n");
5283
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
5284
    let h1 = repo
5285
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
5286
        .unwrap();
5287
    let c1 = repo.store().get_change(&h1).unwrap();
5288
    assert!(
5289
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
5290
        "{:?}",
5291
        c1.tree_ops
5292
    );
5293
    assert_eq!(c1.deps, vec![h0]);
5294
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
5295
    assert!(
5296
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
5297
    );
5298
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
5299
    assert!(!files.contains_key("c.txt"));
5300
    let snap = repo.snapshot("status").unwrap();
5301
    assert_eq!(
5302
        snap.statuses
5303
            .iter()
5304
            .map(|s| (s.path.as_str(), s.status))
5305
            .collect::<Vec<_>>(),
5306
        vec![
5307
            ("b.txt", ChangeStatus::Modified),
5308
            ("c.txt", ChangeStatus::Added)
5309
        ]
5310
    );
5311
    assert_eq!(
5312
        fs::read(root.join("b.txt")).unwrap(),
5313
        b"b\nbb\n",
5314
        "disk untouched"
5315
    );
5316
    // By hunk: pick the b.txt insert; c.txt's addition is left.
5317
    let (_, hunks) = repo.hunks().unwrap();
5318
    let b_hunk = hunks
5319
        .iter()
5320
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
5321
        .unwrap()
5322
        .index;
5323
    let h2 = repo
5324
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
5325
        .unwrap();
5326
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
5327
    assert!(
5328
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
5329
    );
5330
    assert!(!files.contains_key("c.txt"));
5331
    let snap = repo.snapshot("status").unwrap();
5332
    assert_eq!(
5333
        snap.statuses
5334
            .iter()
5335
            .map(|s| s.path.as_str())
5336
            .collect::<Vec<_>>(),
5337
        vec!["c.txt"]
5338
    );
5339
    // Choosing only the content hunk of a file in a new directory pulls in
5340
    // the directory and file additions it needs.
5341
    write(root, "d/e.txt", b"e\n");
5342
    let (_, hunks) = repo.hunks().unwrap();
5343
    let e_insert = hunks
5344
        .iter()
5345
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
5346
        .unwrap()
5347
        .index;
5348
    let h3 = repo
5349
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
5350
        .unwrap();
5351
    let c3 = repo.store().get_change(&h3).unwrap();
5352
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
5353
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
5354
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
5355
    // Choosing a new file's addition hunk brings its content along.
5356
    write(root, "f/g.txt", b"g\n");
5357
    let (_, hunks) = repo.hunks().unwrap();
5358
    let g_add = hunks
5359
        .iter()
5360
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
5361
        .unwrap()
5362
        .index;
5363
    let h4 = repo
5364
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
5365
        .unwrap();
5366
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
5367
    assert!(
5368
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
5369
    );
5370
    assert!(!repo
5371
        .snapshot("status")
5372
        .unwrap()
5373
        .statuses
5374
        .iter()
5375
        .any(|s| s.path == "f/g.txt"));
5376
    // Everything left commits normally; the working copy is then clean.
5377
    repo.commit("the rest", &[]).unwrap();
5378
    assert!(!repo.snapshot("status").unwrap().changed);
5379
    let files = repo
5380
        .load_state(&repo.bookmark_heads().unwrap())
5381
        .unwrap()
5382
        .materialize()
5383
        .files;
5384
    assert!(files.contains_key("c.txt"));
5385
}
5386
5387
#[test]
5388
fn blame_attributes_lines_to_introducing_changes_across_renames() {
5389
    hermetic();
5390
    let dir = tempfile::tempdir().unwrap();
5391
    let root = dir.path();
5392
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5393
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
5394
        .unwrap();
5395
    write(root, "a.txt", b"one\n");
5396
    let h1 = repo.commit("first", &[]).unwrap();
5397
    write(root, "a.txt", b"one\ntwo\n");
5398
    let h2 = repo.commit("second", &[]).unwrap();
5399
    let b = repo.blame("a.txt").unwrap();
5400
    assert_eq!(
5401
        b.iter()
5402
            .map(|l| (l.line, l.hash, l.text.as_slice()))
5403
            .collect::<Vec<_>>(),
5404
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
5405
    );
5406
    assert!(b.iter().all(|l| l.author == "Ada"));
5407
    assert_eq!(
5408
        b[0].change_id,
5409
        repo.store().get_change(&h1).unwrap().change_id
5410
    );
5411
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
5412
    repo.commit("rename", &[]).unwrap();
5413
    let b = repo.blame("b.txt").unwrap();
5414
    assert_eq!(
5415
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
5416
        vec![h1, h2],
5417
        "the node survives the rename"
5418
    );
5419
    assert!(repo.blame("a.txt").is_err());
5420
}
5421
5422
#[test]
5423
fn bisect_finds_the_first_bad_change() {
5424
    hermetic();
5425
    let dir = tempfile::tempdir().unwrap();
5426
    let root = dir.path();
5427
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5428
    let mut content = String::new();
5429
    let mut hashes = Vec::new();
5430
    for i in 1..=8 {
5431
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
5432
        write(root, "f.txt", content.as_bytes());
5433
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
5434
    }
5435
    // Each step appends after the previous line, so the chain is linear.
5436
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
5437
    repo.bisect_start().unwrap();
5438
    assert!(matches!(
5439
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
5440
        BisectStep::NeedMarks { good: 1, bad: 0 }
5441
    ));
5442
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
5443
    assert!(
5444
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
5445
        "{step:?}"
5446
    );
5447
    // Automated: bad when the bug line is present.
5448
    let step = repo
5449
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
5450
        .unwrap();
5451
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
5452
    assert_eq!(
5453
        repo.bisect_status().unwrap(),
5454
        Some(BisectStep::Found { culprit: hashes[4] })
5455
    );
5456
    repo.bisect_reset().unwrap();
5457
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
5458
    assert!(repo.bisect_status().unwrap().is_none());
5459
    assert!(!repo.snapshot("status").unwrap().changed);
5460
    // Manual marks and a skip.
5461
    repo.bisect_start().unwrap();
5462
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
5463
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
5464
    let mut skipped_once = false;
5465
    let mut guard = 0;
5466
    while let BisectStep::Testing { .. } = step {
5467
        guard += 1;
5468
        assert!(guard < 20);
5469
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
5470
        if !skipped_once && text.contains("line 6") {
5471
            // An untestable state away from the boundary: the search routes around it.
5472
            skipped_once = true;
5473
            step = repo.bisect_mark(None, &[]).unwrap();
5474
            continue;
5475
        }
5476
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
5477
    }
5478
    assert!(skipped_once);
5479
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
5480
    repo.bisect_reset().unwrap();
5481
    // Skipping the culprit itself leaves it among the candidates reported.
5482
    repo.bisect_start().unwrap();
5483
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
5484
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
5485
    let mut guard = 0;
5486
    while let BisectStep::Testing { heads, .. } = &step {
5487
        guard += 1;
5488
        assert!(guard < 20);
5489
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
5490
        let is_culprit_state =
5491
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
5492
        step = if is_culprit_state {
5493
            repo.bisect_mark(None, &[]).unwrap()
5494
        } else {
5495
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
5496
        };
5497
    }
5498
    match step {
5499
        BisectStep::Inconclusive { candidates } => assert!(
5500
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
5501
            "{candidates:?}"
5502
        ),
5503
        other => panic!("{other:?}"),
5504
    }
5505
    repo.bisect_reset().unwrap();
5506
}
5507
5508
#[test]
5509
fn squash_folds_a_change_into_its_dependency() {
5510
    hermetic();
5511
    let dir = tempfile::tempdir().unwrap();
5512
    let root = dir.path();
5513
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5514
    write(root, "a.txt", b"1\n");
5515
    let a = repo.commit("A", &[]).unwrap();
5516
    write(root, "a.txt", b"1\n2\n");
5517
    let c = repo.commit("C", &[]).unwrap();
5518
    write(root, "a.txt", b"1\n2\n3\n");
5519
    let e = repo.commit("E", &[]).unwrap();
5520
    write(root, "b.txt", b"b\n");
5521
    let b = repo.commit("B", &[]).unwrap();
5522
    let id_a = repo.store().get_change(&a).unwrap().change_id;
5523
    let id_e = repo.store().get_change(&e).unwrap().change_id;
5524
    // E depends on C which A lacks: refused, naming it.
5525
    let err = repo.squash(&e, &a).unwrap_err().to_string();
5526
    assert!(err.contains(&c.short(12)), "{err}");
5527
    // C into A: A' has both, C is gone, E follows and still reads the same.
5528
    let a2 = repo.squash(&c, &a).unwrap();
5529
    let a2c = repo.store().get_change(&a2).unwrap();
5530
    assert_eq!(a2c.change_id, id_a);
5531
    assert!(a2c.deps.is_empty());
5532
    let heads = repo.bookmark_heads().unwrap();
5533
    let st = repo.load_state(&heads).unwrap();
5534
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
5535
    let e2 = st
5536
        .changes()
5537
        .find(|(_, m)| m.change_id == id_e)
5538
        .map(|(h, _)| *h)
5539
        .unwrap();
5540
    assert_eq!(
5541
        repo.store().get_change(&e2).unwrap().deps,
5542
        vec![a2],
5543
        "E now depends on A' alone"
5544
    );
5545
    let files = st.materialize().files;
5546
    assert!(
5547
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
5548
    );
5549
    assert!(files.contains_key("b.txt"));
5550
    assert!(st.contains(&b));
5551
    assert!(!repo.snapshot("status").unwrap().changed);
5552
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
5553
    // Undo restores the three original changes.
5554
    repo.undo().unwrap();
5555
    repo.undo().unwrap();
5556
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
5557
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
5558
}
5559
5560
#[test]
5561
fn rebase_re_expresses_a_change_against_another_base() {
5562
    hermetic();
5563
    let dir = tempfile::tempdir().unwrap();
5564
    let root = dir.path();
5565
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5566
    write(root, "a.txt", b"1\n2\n");
5567
    let a = repo.commit("A", &[]).unwrap();
5568
    write(root, "a.txt", b"1\n2\n3\n");
5569
    let c = repo.commit("C: append 3", &[]).unwrap();
5570
    write(root, "a.txt", b"1\n2\n3\n4\n");
5571
    let e = repo.commit("E: append 4", &[]).unwrap();
5572
    // A different base: A plus a change that prepends a line.
5573
    repo.checkout(&[a], true, "checkout").unwrap();
5574
    write(root, "a.txt", b"0\n1\n2\n");
5575
    let d = repo.commit("D: prepend 0", &[]).unwrap();
5576
    let id_c = repo.store().get_change(&c).unwrap().change_id;
5577
    let id_e = repo.store().get_change(&e).unwrap().change_id;
5578
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
5579
    let c2 = repo.rebase(&c, &[d]).unwrap();
5580
    let c2c = repo.store().get_change(&c2).unwrap();
5581
    assert_eq!(c2c.change_id, id_c);
5582
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
5583
    let heads = repo.bookmark_heads().unwrap();
5584
    let st = repo.load_state(&heads).unwrap();
5585
    assert!(!st.contains(&c) && st.contains(&d));
5586
    let e2 = st
5587
        .changes()
5588
        .find(|(_, m)| m.change_id == id_e)
5589
        .map(|(h, _)| *h)
5590
        .unwrap();
5591
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
5592
    assert!(
5593
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
5594
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
5595
    );
5596
    let files = st.materialize().files;
5597
    assert!(
5598
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
5599
        "{:?}",
5600
        files["a.txt"].content
5601
    );
5602
    assert!(!files["a.txt"].is_conflicted());
5603
    // Rebasing onto a state that already contains the change is refused.
5604
    assert!(repo.rebase(&c2, &[c2]).is_err());
5605
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
5606
    assert!(
5607
        err.contains("lacks dependencies"),
5608
        "E needs C, which D's state does not have: {err}"
5609
    );
5610
}
5611
5612
#[test]
5613
fn unsigned_tags_keep_their_message() {
5614
    hermetic();
5615
    let dir = tempfile::tempdir().unwrap();
5616
    let root = dir.path();
5617
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5618
    write(root, "a.txt", b"a\n");
5619
    repo.commit("a", &[]).unwrap();
5620
    assert!(repo.secret_key().unwrap().is_none());
5621
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
5622
        .unwrap();
5623
    let tags = repo.tags().unwrap();
5624
    assert_eq!(
5625
        (
5626
            tags[0].name.as_str(),
5627
            tags[0].message.as_str(),
5628
            tags[0].signer.as_deref()
5629
        ),
5630
        ("v1", "first release", None)
5631
    );
5632
    assert!(
5633
        repo.tag_refs().unwrap()[0].attestation.is_none(),
5634
        "an unsigned attestation is not advertised"
5635
    );
5636
}
5637
5638
#[test]
5639
fn fsck_passes_a_sound_repository_and_names_each_fault() {
5640
    // Files on disk are what this tests: tampering with them, and the
5641
    // directory store's crash points.
5642
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
5643
        return;
5644
    }
5645
    hermetic();
5646
    let dir = tempfile::tempdir().unwrap();
5647
    let root = dir.path();
5648
    let origin_path = root.join("origin");
5649
    let origin = Repo::init(&origin_path).unwrap();
5650
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
5651
        .unwrap()
5652
        .with_home(root.join("home-a"));
5653
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5654
        .unwrap();
5655
    write(&root.join("a"), "f.txt", b"one\n");
5656
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
5657
    let h1 = a.commit("first", &[]).unwrap();
5658
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
5659
    let h2 = a.commit("second", &[]).unwrap();
5660
    a.tag_create("v1", &[h2], "first release").unwrap();
5661
    a.checkpoint().unwrap();
5662
    assert!(a.push("origin", false).unwrap()[0].ok);
5663
    origin.refresh().unwrap();
5664
5665
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
5666
    for repo in [&a, &origin] {
5667
        let rep = repo.fsck().unwrap();
5668
        assert_eq!(rep.problems, vec![], "{rep:?}");
5669
        // The two commits, plus the working copy's change in `a`.
5670
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
5671
        assert!(rep.ops > 1 && rep.objects > 5);
5672
    }
5673
    assert!(origin.fsck().unwrap().attestations >= 1);
5674
5675
    // A flipped byte in a stored object is corruption, named by hash.
5676
    let c1 = a.store().path_for(&h1);
5677
    let pristine = fs::read(&c1).unwrap();
5678
    let mut bytes = pristine.clone();
5679
    *bytes.last_mut().unwrap() ^= 1;
5680
    fs::write(&c1, &bytes).unwrap();
5681
    let rep = a.fsck().unwrap();
5682
    assert!(rep.errors() >= 1);
5683
    assert!(
5684
        rep.problems
5685
            .iter()
5686
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
5687
        "{rep:?}"
5688
    );
5689
    fs::write(&c1, &pristine).unwrap();
5690
    assert_eq!(a.fsck().unwrap().errors(), 0);
5691
5692
    // A missing change is named with what needed it.
5693
    fs::remove_file(&c1).unwrap();
5694
    let rep = a.fsck().unwrap();
5695
    assert!(
5696
        rep.problems.iter().any(|p| p.severity == Severity::Error
5697
            && p.object == Some(h1)
5698
            && p.what.contains("change missing, needed by change")),
5699
        "{rep:?}"
5700
    );
5701
    fs::write(&c1, &pristine).unwrap();
5702
5703
    // A missing blob is an error in a full clone.
5704
    let c2 = a.store().get_change(&h1).unwrap();
5705
    let blob = c2
5706
        .edits
5707
        .iter()
5708
        .find_map(|e| match e {
5709
            Edit::Replace { new: Some(b), .. } => Some(*b),
5710
            _ => None,
5711
        })
5712
        .expect("the binary file is a blob");
5713
    let bp = a.store().path_for(&blob);
5714
    let blob_bytes = fs::read(&bp).unwrap();
5715
    fs::remove_file(&bp).unwrap();
5716
    let rep = a.fsck().unwrap();
5717
    assert!(
5718
        rep.problems
5719
            .iter()
5720
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
5721
        "{rep:?}"
5722
    );
5723
    fs::write(&bp, &blob_bytes).unwrap();
5724
5725
    // A broken op log head is reported, not a crash.
5726
    let head = root.join("a/.oxy/ops/head");
5727
    let saved = fs::read(&head).unwrap();
5728
    fs::write(&head, b"not a hash").unwrap();
5729
    let rep = a.fsck().unwrap();
5730
    assert!(
5731
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
5732
        "{rep:?}"
5733
    );
5734
    fs::write(&head, saved).unwrap();
5735
    assert_eq!(a.fsck().unwrap().problems, vec![]);
5736
}
5737
5738
/// Copy a directory tree (for restoring a pristine repository).
5739
fn copy_tree(from: &Path, to: &Path) {
5740
    fs::create_dir_all(to).unwrap();
5741
    for e in fs::read_dir(from).unwrap() {
5742
        let e = e.unwrap();
5743
        let target = to.join(e.file_name());
5744
        if e.file_type().unwrap().is_dir() {
5745
            copy_tree(&e.path(), &target);
5746
        } else {
5747
            fs::copy(e.path(), &target).unwrap();
5748
        }
5749
    }
5750
}
5751
5752
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
5753
/// would, and check that both repositories still open, pass `fsck`, and
5754
/// accept the same operation again.
5755
#[test]
5756
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
5757
    // Files on disk are what this tests: tampering with them, and the
5758
    // directory store's crash points.
5759
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
5760
        return;
5761
    }
5762
    use crate::durable::failpoint;
5763
    hermetic();
5764
    let dir = tempfile::tempdir().unwrap();
5765
    let pristine = dir.path().join("pristine");
5766
    let origin_path = pristine.join("origin");
5767
    Repo::init(&origin_path).unwrap();
5768
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
5769
        .unwrap()
5770
        .with_home(dir.path().join("home"));
5771
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5772
        .unwrap();
5773
    write(&pristine.join("a"), "f.txt", b"one\n");
5774
    a.commit("first", &[]).unwrap();
5775
    assert!(a.push("origin", false).unwrap()[0].ok);
5776
    drop(a);
5777
5778
    type Op = fn(&Repo) -> Result<()>;
5779
    let edit_and_commit: Op = |r| {
5780
        write(r.root(), "f.txt", b"one\ntwo\n");
5781
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
5782
        r.commit("second", &[]).map(|_| ())
5783
    };
5784
    let push: Op = |r| {
5785
        let res = r.push("origin", false)?;
5786
        if res.iter().all(|x| x.ok) {
5787
            Ok(())
5788
        } else {
5789
            Err(RepoError::Msg(format!("{res:?}")))
5790
        }
5791
    };
5792
5793
    for (name, prepare, op) in [
5794
        ("commit", None, edit_and_commit),
5795
        ("push", Some(edit_and_commit), push),
5796
    ] {
5797
        let mut steps = 0;
5798
        for n in 1.. {
5799
            let run = dir.path().join(format!("{name}-{n}"));
5800
            copy_tree(&pristine, &run);
5801
            // Clones record their remote by path; point it at this copy.
5802
            let open = |p: &Path| {
5803
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
5804
                r.config
5805
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
5806
                    .unwrap();
5807
                r.save_config().unwrap();
5808
                r
5809
            };
5810
            let a = open(&run.join("a"));
5811
            if let Some(prep) = prepare {
5812
                prep(&a).unwrap();
5813
            }
5814
            failpoint::crash_after(n);
5815
            let outcome = op(&a);
5816
            let crashed = failpoint::disarm();
5817
            drop(a);
5818
            if !crashed {
5819
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
5820
                steps = n - 1;
5821
                break;
5822
            }
5823
            assert!(
5824
                outcome.is_err(),
5825
                "{name}: a crash at step {n} was swallowed"
5826
            );
5827
            for repo in ["a", "origin"] {
5828
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
5829
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
5830
                });
5831
                let rep = r.fsck().unwrap();
5832
                assert_eq!(
5833
                    rep.errors(),
5834
                    0,
5835
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
5836
                    rep.problems
5837
                );
5838
            }
5839
            // The interrupted operation can simply be run again.
5840
            let a = open(&run.join("a"));
5841
            // A crash after the commit point leaves the commit done.
5842
            let landed = a
5843
                .bookmark_heads()
5844
                .unwrap()
5845
                .iter()
5846
                .any(|h| a.store().get_change(h).unwrap().message == "second");
5847
            let again = match (name, landed) {
5848
                ("commit", true) => Ok(()),
5849
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
5850
                _ => op(&a),
5851
            };
5852
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
5853
            assert_eq!(a.fsck().unwrap().errors(), 0);
5854
            fs::remove_dir_all(&run).unwrap();
5855
        }
5856
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
5857
    }
5858
}
5859
5860
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
5861
/// running at the same time lose nothing: every commit ends up on the
5862
/// bookmark, locally and on the remote, and the repository passes fsck.
5863
#[test]
5864
fn concurrent_commits_in_two_workspaces_lose_nothing() {
5865
    hermetic();
5866
    let dir = tempfile::tempdir().unwrap();
5867
    let root = dir.path();
5868
    let origin = root.join("origin");
5869
    Repo::init_bare_unbound(&origin).unwrap();
5870
    let main = root.join("main");
5871
    let mut repo = Repo::init(&main).unwrap();
5872
    repo.config
5873
        .set("remote.origin.url", &origin.to_string_lossy())
5874
        .unwrap();
5875
    repo.save_config().unwrap();
5876
    write(&main, "seed.txt", b"seed\n");
5877
    repo.commit("seed", &[]).unwrap();
5878
    let second = root.join("second");
5879
    repo.workspace_add(&second, None).unwrap();
5880
    drop(repo);
5881
5882
    const EACH: usize = 15;
5883
    std::thread::scope(|s| {
5884
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
5885
            s.spawn(move || {
5886
                let r = Repo::open(&dir).unwrap();
5887
                for i in 0..EACH {
5888
                    write(
5889
                        &dir,
5890
                        &format!("{tag}-{i}.txt"),
5891
                        format!("{tag} {i}\n").as_bytes(),
5892
                    );
5893
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
5894
                    if push && i % 5 == 4 {
5895
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
5896
                        let _ = r.push("origin", false);
5897
                    }
5898
                }
5899
            });
5900
        }
5901
    });
5902
5903
    let repo = Repo::open(&main).unwrap();
5904
    let heads = repo.bookmark_heads().unwrap();
5905
    let state = repo.load_state(&heads).unwrap();
5906
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
5907
    for tag in ["a", "b"] {
5908
        for i in 0..EACH {
5909
            assert!(
5910
                messages.contains(&format!("{tag} {i}")),
5911
                "lost commit {tag} {i}; have {messages:?}"
5912
            );
5913
        }
5914
    }
5915
    let rep = repo.fsck().unwrap();
5916
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
5917
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
5918
    let hosted = Repo::open(&origin).unwrap();
5919
    let hosted_heads = hosted.bookmark_heads().unwrap();
5920
    assert_eq!(
5921
        hosted.load_state(&hosted_heads).unwrap().len(),
5922
        state.len(),
5923
        "the remote has every commit"
5924
    );
5925
}
5926
5927
/// Two operations recorded from the same parent (what two processes do
5928
/// when they race) are merged: both bookmarks' heads survive, and a
5929
/// change made on one side only is kept.
5930
#[test]
5931
fn operations_from_the_same_parent_are_merged() {
5932
    hermetic();
5933
    let dir = tempfile::tempdir().unwrap();
5934
    let root = dir.path();
5935
    let repo = Repo::init(root).unwrap();
5936
    write(root, "a.txt", b"a\n");
5937
    let a = repo.commit("a", &[]).unwrap();
5938
    write(root, "b.txt", b"b\n");
5939
    let b = repo.commit("b", &[]).unwrap();
5940
    let (x, op) = repo.head_op().unwrap();
5941
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
5942
5943
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
5944
    let mut one = op.view.clone();
5945
    one.bookmarks.insert("main".into(), state(vec![a]));
5946
    one.bookmarks.insert("topic".into(), state(vec![a]));
5947
    let mut two = op.view.clone();
5948
    two.bookmarks.insert("main".into(), state(vec![b]));
5949
    repo.record_op(&[x], "one", one).unwrap();
5950
    let merged = repo.record_op(&[x], "two", two).unwrap();
5951
5952
    let (head, op) = repo.head_op().unwrap();
5953
    assert_eq!(head, merged);
5954
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
5955
    assert!(op.command.contains("merged with a concurrent operation"));
5956
    let mut main = repo
5957
        .store()
5958
        .get_state(&op.view.bookmarks["main"])
5959
        .unwrap()
5960
        .heads;
5961
    main.sort();
5962
    let mut want = vec![a, b];
5963
    want.sort();
5964
    assert_eq!(main, want, "both sides' heads are kept");
5965
    assert!(
5966
        op.view.bookmarks.contains_key("topic"),
5967
        "a one-sided change survives"
5968
    );
5969
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5970
}
5971
5972
#[test]
5973
fn failed_requests_come_with_a_next_step() {
5974
    use crate::protocol::hint_for;
5975
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
5976
        .unwrap()
5977
        .contains("token"));
5978
    assert!(hint_for("…: HTTP 403: forbidden")
5979
        .unwrap()
5980
        .contains("repo:write"));
5981
    assert!(hint_for("…: HTTP 404: no such repository")
5982
        .unwrap()
5983
        .contains("owner and repository name"));
5984
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
5985
        .unwrap()
5986
        .contains("oxyhub-ca.pem"));
5987
    assert!(hint_for("Connect error: Connection refused (os error 111)")
5988
        .unwrap()
5989
        .contains("running"));
5990
    assert!(hint_for("Dns Failed: failed to lookup address information")
5991
        .unwrap()
5992
        .contains("resolve"));
5993
    assert_eq!(hint_for("something else entirely"), None);
5994
}
5995
5996
#[test]
5997
fn doctor_names_problems_and_what_to_do() {
5998
    hermetic();
5999
    let dir = tempfile::tempdir().unwrap();
6000
    let root = dir.path();
6001
    let origin = root.join("origin");
6002
    Repo::init_bare_unbound(&origin).unwrap();
6003
    let mut repo = Repo::init(&root.join("r"))
6004
        .unwrap()
6005
        .with_home(root.join("home"));
6006
    let find = |r: &DoctorReport, area: &str, h: Health| {
6007
        r.checks
6008
            .iter()
6009
            .find(|c| c.area == area && c.health == h)
6010
            .cloned()
6011
    };
6012
6013
    let r = repo.doctor(true);
6014
    assert!(find(&r, "identity", Health::Warn)
6015
        .unwrap()
6016
        .hint
6017
        .unwrap()
6018
        .contains("oxy identity create"));
6019
    assert!(find(&r, "repository", Health::Ok).is_some());
6020
    // oxygen#127: no policy is said, with who sets one.
6021
    assert!(find(&r, "trust", Health::Warn)
6022
        .unwrap()
6023
        .hint
6024
        .unwrap()
6025
        .contains("oxy policy init"));
6026
6027
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6028
        .unwrap();
6029
    repo.policy_init().unwrap();
6030
    let r = repo.doctor(false);
6031
    let trust = find(&r, "trust", Health::Ok).expect("a fresh policy is fine");
6032
    assert!(
6033
        trust.message.contains("serial 1") && trust.message.contains("1 root"),
6034
        "{trust:?}"
6035
    );
6036
    repo.config.set("author.name", "Ada").unwrap();
6037
    repo.config.set("author.email", "[email protected]").unwrap();
6038
    repo.config
6039
        .set("remote.origin.url", &origin.to_string_lossy())
6040
        .unwrap();
6041
    repo.config
6042
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
6043
        .unwrap();
6044
    repo.config.set("remote.down.token", "t").unwrap();
6045
    repo.config
6046
        .set("remote.badca.url", "https://example.invalid/a/b")
6047
        .unwrap();
6048
    repo.config
6049
        .set(
6050
            "remote.badca.ca",
6051
            &root.join("missing.pem").to_string_lossy(),
6052
        )
6053
        .unwrap();
6054
    repo.save_config().unwrap();
6055
6056
    let r = repo.doctor(true);
6057
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
6058
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
6059
    assert!(find(&r, "remote origin", Health::Ok)
6060
        .unwrap()
6061
        .message
6062
        .contains("first push binds it"));
6063
    let down = find(&r, "remote down", Health::Fail).unwrap();
6064
    assert!(
6065
        down.hint.as_deref().unwrap_or("").contains("running"),
6066
        "{down:?}"
6067
    );
6068
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
6069
    assert!(
6070
        badca.hint.unwrap().contains("remote.badca.ca"),
6071
        "the remote's own name is in the hint"
6072
    );
6073
    assert_eq!(r.worst(), Health::Fail);
6074
6075
    // Offline, nothing is contacted.
6076
    let r = repo.doctor(false);
6077
    assert!(find(&r, "remote down", Health::Fail).is_none());
6078
    assert!(find(&r, "remote down", Health::Ok)
6079
        .unwrap()
6080
        .message
6081
        .contains("not contacted"));
6082
}
6083
6084
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
6085
/// after it. Inserting after `b` and then deleting `b`, one commit after
6086
/// the other, must not leave a delete/insert conflict.
6087
#[test]
6088
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
6089
    hermetic();
6090
    let dir = tempfile::tempdir().unwrap();
6091
    let root = dir.path();
6092
    let repo = Repo::init(root).unwrap();
6093
    write(root, "f", b"a\nb\nc\n");
6094
    repo.commit("base", &[]).unwrap();
6095
    write(root, "f", b"a\nb\nx\nc\n");
6096
    let insert = repo.commit("insert x after b", &[]).unwrap();
6097
    write(root, "f", b"a\nx\nc\n");
6098
    let delete = repo.commit("delete b", &[]).unwrap();
6099
    assert!(
6100
        repo.store()
6101
            .get_change(&delete)
6102
            .unwrap()
6103
            .deps
6104
            .contains(&insert),
6105
        "the deletion depends on the insertion below the deleted line"
6106
    );
6107
    let heads = repo.bookmark_heads().unwrap();
6108
    assert_eq!(heads, vec![delete]);
6109
    let snap = repo.load_state(&heads).unwrap().materialize();
6110
    assert!(!snap.is_conflicted());
6111
    assert!(
6112
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
6113
    );
6114
}
6115
6116
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
6117
/// replacement depends on the change that set the blob it replaces.
6118
#[test]
6119
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
6120
    hermetic();
6121
    let dir = tempfile::tempdir().unwrap();
6122
    let root = dir.path();
6123
    let repo = Repo::init(root).unwrap();
6124
    write(root, "bin", b"\0A");
6125
    let v1 = repo.commit("v1", &[]).unwrap();
6126
    write(root, "bin", b"\0B");
6127
    let v2 = repo.commit("v2", &[]).unwrap();
6128
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
6129
    write(root, "bin", b"\0A");
6130
    let v3 = repo.commit("back to A", &[]).unwrap();
6131
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
6132
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
6133
    let state = repo.load_state(&[v3]).unwrap();
6134
    let snap = state.materialize();
6135
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
6136
        panic!("opaque")
6137
    };
6138
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
6139
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
6140
}
6141
6142
/// Spec §23: a binary file changed on two branches and merged in Git to
6143
/// one side's version comes back as that version at the merge, and the
6144
/// import verifies commit by commit.
6145
#[test]
6146
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
6147
    hermetic();
6148
    if std::process::Command::new("git")
6149
        .arg("--version")
6150
        .output()
6151
        .is_err()
6152
    {
6153
        eprintln!("git not installed; skipping");
6154
        return;
6155
    }
6156
    let dir = tempfile::tempdir().unwrap();
6157
    let root = dir.path();
6158
    let g = root.join("src.git");
6159
    fs::create_dir_all(&g).unwrap();
6160
    let git = |args: &[&str]| -> String {
6161
        let out = std::process::Command::new("git")
6162
            .arg("-C")
6163
            .arg(&g)
6164
            .args([
6165
                "-c",
6166
                "user.name=Grace",
6167
                "-c",
6168
                "[email protected]",
6169
                "-c",
6170
                "commit.gpgsign=false",
6171
            ])
6172
            .args(args)
6173
            .output()
6174
            .unwrap();
6175
        assert!(
6176
            out.status.success(),
6177
            "git {args:?}: {}",
6178
            String::from_utf8_lossy(&out.stderr)
6179
        );
6180
        String::from_utf8_lossy(&out.stdout).trim().to_string()
6181
    };
6182
    git(&["init", "-q", "-b", "main"]);
6183
    write(&g, "logo.bin", b"\0base");
6184
    write(&g, "notes.txt", b"a\nb\nc\n");
6185
    git(&["add", "."]);
6186
    git(&["commit", "-qm", "base"]);
6187
    git(&["checkout", "-qb", "side"]);
6188
    write(&g, "logo.bin", b"\0side");
6189
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
6190
    git(&["commit", "-qam", "side"]);
6191
    git(&["checkout", "-q", "main"]);
6192
    write(&g, "logo.bin", b"\0main");
6193
    git(&["commit", "-qam", "main"]);
6194
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
6195
    let _ = std::process::Command::new("git")
6196
        .arg("-C")
6197
        .arg(&g)
6198
        .args([
6199
            "-c",
6200
            "user.name=G",
6201
            "-c",
6202
            "user.email=g@e",
6203
            "merge",
6204
            "-q",
6205
            "side",
6206
        ])
6207
        .output();
6208
    write(&g, "logo.bin", b"\0main");
6209
    git(&["add", "."]);
6210
    git(&["commit", "-qm", "merge side"]);
6211
    // Then a revert of the binary to its first version.
6212
    write(&g, "logo.bin", b"\0base");
6213
    git(&["commit", "-qam", "back to base"]);
6214
6215
    let repo = Repo::init(&root.join("o")).unwrap();
6216
    let rep = repo.import_git(&g, "main").unwrap();
6217
    assert_eq!(rep.merges, 1);
6218
    let v = repo.verify_git_import(&g, "main").unwrap();
6219
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6220
    assert_eq!(v.commits, 5);
6221
    let snap = repo
6222
        .load_state(&repo.bookmark_heads().unwrap())
6223
        .unwrap()
6224
        .materialize();
6225
    assert!(!snap.is_conflicted());
6226
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
6227
        panic!("opaque")
6228
    };
6229
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
6230
}
6231
6232
/// Spec §7.7 on a file system without executable bits or symlinks: the
6233
/// recorded bit is kept, and a symlink checked out as a plain file holding
6234
/// its target is still that symlink.
6235
#[cfg(unix)]
6236
#[test]
6237
fn windows_file_systems_keep_exec_bits_and_symlinks() {
6238
    use crate::portable::Platform;
6239
    use std::os::unix::fs::PermissionsExt;
6240
    hermetic();
6241
    let dir = tempfile::tempdir().unwrap();
6242
    let root = dir.path();
6243
    let repo = Repo::init(root).unwrap();
6244
    write(root, "run.sh", b"#!/bin/sh\n");
6245
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
6246
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
6247
    repo.commit("script and link", &[]).unwrap();
6248
    drop(repo);
6249
6250
    // What checking out on Windows leaves: no exec bit, the link as a file.
6251
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
6252
    fs::remove_file(root.join("link")).unwrap();
6253
    write(root, "link", b"run.sh");
6254
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
6255
    let s = win.snapshot("oxy status").unwrap();
6256
    assert!(
6257
        s.statuses.is_empty(),
6258
        "nothing changed on Windows: {:?}",
6259
        statuses(&s)
6260
    );
6261
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
6262
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
6263
    write(root, "link", b"other");
6264
    let h = win.commit("edit on Windows", &[]).unwrap();
6265
    let snap = win.load_state(&[h]).unwrap().materialize();
6266
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
6267
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
6268
    // The same working copy read as Linux sees the lost bit and the plain file.
6269
    let linux = Repo::open(root).unwrap();
6270
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
6271
}
6272
6273
/// Paths that collide on case-insensitive or Windows file systems are
6274
/// named at checkout there, and by doctor everywhere.
6275
#[test]
6276
fn paths_other_platforms_cannot_hold_are_reported() {
6277
    use crate::portable::Platform;
6278
    hermetic();
6279
    let dir = tempfile::tempdir().unwrap();
6280
    let root = dir.path();
6281
    let repo = Repo::init(root).unwrap();
6282
    write(root, "README.md", b"a\n");
6283
    write(root, "readme.md", b"b\n");
6284
    write(root, "src/aux.c", b"int x;\n");
6285
    let h = repo.commit("unportable", &[]).unwrap();
6286
    let r = repo.doctor(false);
6287
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
6288
    assert_eq!(port.health, Health::Warn);
6289
    assert!(
6290
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
6291
        "{}",
6292
        port.message
6293
    );
6294
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
6295
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
6296
    assert!(
6297
        rep.notes
6298
            .iter()
6299
            .any(|n| n.contains("README.md and readme.md")),
6300
        "{:?}",
6301
        rep.notes
6302
    );
6303
    assert!(
6304
        !rep.notes.iter().any(|n| n.contains("aux.c")),
6305
        "macOS allows aux.c"
6306
    );
6307
}
6308
6309
#[test]
6310
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
6311
    hermetic();
6312
    let dir = tempfile::tempdir().unwrap();
6313
    let repo = Repo::init(dir.path()).unwrap();
6314
    write(dir.path(), "a.txt", b"one\n");
6315
    write(dir.path(), "other.txt", b"x\n");
6316
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
6317
    repo.snapshot("t").unwrap();
6318
    let c1 = repo.commit("first", &[]).unwrap();
6319
    write(dir.path(), "other.txt", b"y\n");
6320
    repo.snapshot("t").unwrap();
6321
    repo.commit("other only", &[]).unwrap();
6322
    write(dir.path(), "a.txt", b"one\ntwo\n");
6323
    repo.snapshot("t").unwrap();
6324
    let c3 = repo.commit("second line", &[]).unwrap();
6325
    write(dir.path(), "other.txt", b"z\n");
6326
    repo.snapshot("t").unwrap();
6327
    repo.commit("other again", &[]).unwrap();
6328
6329
    let heads = repo.bookmark_heads().unwrap();
6330
    let state = repo.load_state(&heads).unwrap();
6331
    let full: Vec<ChangeHash> = repo
6332
        .log_for_path_in("a.txt", &heads)
6333
        .unwrap()
6334
        .iter()
6335
        .map(|e| e.hash)
6336
        .collect();
6337
    assert_eq!(
6338
        full,
6339
        vec![c3, c1],
6340
        "newest first, only changes touching the path"
6341
    );
6342
    let newest: Vec<ChangeHash> = repo
6343
        .log_for_path_of(&state, "a.txt", Some(1))
6344
        .unwrap()
6345
        .iter()
6346
        .map(|e| e.hash)
6347
        .collect();
6348
    assert_eq!(newest, vec![c3], "stops at the first");
6349
    assert_eq!(
6350
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
6351
        2
6352
    );
6353
    assert!(repo
6354
        .log_for_path_of(&state, "missing.txt", Some(1))
6355
        .is_err());
6356
    assert_eq!(
6357
        repo.log_state(&heads).unwrap().len(),
6358
        repo.log_of(&state).len()
6359
    );
6360
6361
    let tree = state.tree().view();
6362
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
6363
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
6364
    assert_eq!(
6365
        via_state
6366
            .iter()
6367
            .map(|l| (l.hash, l.text.clone()))
6368
            .collect::<Vec<_>>(),
6369
        via_heads
6370
            .iter()
6371
            .map(|l| (l.hash, l.text.clone()))
6372
            .collect::<Vec<_>>()
6373
    );
6374
    assert_eq!(
6375
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
6376
        vec![c1, c3]
6377
    );
6378
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
6379
}
6380
6381
/// A text file whose stat matches the manifest and whose recorded hash is
6382
/// the base's content is taken from the base without reading it; anything
6383
/// else is read, so no edit is missed (spec §12.3).
6384
#[cfg(unix)]
6385
#[test]
6386
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
6387
    use std::os::unix::fs::PermissionsExt;
6388
    hermetic();
6389
    let dir = tempfile::tempdir().unwrap();
6390
    let root = dir.path();
6391
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6392
    write(root, "a.txt", b"one\ntwo\n");
6393
    write(root, "b.txt", b"bee\n");
6394
    repo.commit("base", &[]).unwrap();
6395
    let age = |p: &str| {
6396
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6397
        fs::File::options()
6398
            .write(true)
6399
            .open(root.join(p))
6400
            .unwrap()
6401
            .set_modified(old)
6402
            .unwrap();
6403
    };
6404
    age("a.txt");
6405
    age("b.txt");
6406
    assert!(
6407
        !repo.snapshot("status").unwrap().changed,
6408
        "records the aged stat"
6409
    );
6410
6411
    // Clean and equal to the base: not read at all.
6412
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6413
    let snap = repo.snapshot("status").unwrap();
6414
    assert!(
6415
        !snap.changed && snap.statuses.is_empty(),
6416
        "{:?}",
6417
        snap.statuses
6418
    );
6419
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6420
6421
    // An uncommitted edit that is older than the manifest: stat-clean, but
6422
    // its hash is not the base's, so it is read and stays visible.
6423
    write(root, "b.txt", b"bee edited\n");
6424
    age("b.txt");
6425
    let first = repo.snapshot("status").unwrap();
6426
    assert_eq!(
6427
        statuses(&first),
6428
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
6429
    );
6430
    let again = repo.snapshot("status").unwrap();
6431
    assert_eq!(
6432
        statuses(&again),
6433
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
6434
        "still seen once stat-clean"
6435
    );
6436
    assert!(!again.changed, "and the working copy hashes the same");
6437
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6438
    assert!(
6439
        repo.snapshot("status").is_err(),
6440
        "an edited file must be read, never taken from the base"
6441
    );
6442
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6443
6444
    // A same-size edit made just now is racy and read.
6445
    write(root, "a.txt", b"one\nTWO\n");
6446
    assert_eq!(
6447
        statuses(&repo.snapshot("status").unwrap()),
6448
        vec![
6449
            ("a.txt".to_string(), ChangeStatus::Modified),
6450
            ("b.txt".to_string(), ChangeStatus::Modified)
6451
        ]
6452
    );
6453
    // Committing makes the edits the base: both are clean and served from it again.
6454
    repo.commit("edits", &[]).unwrap();
6455
    age("a.txt");
6456
    age("b.txt");
6457
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
6458
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6459
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6460
    let snap = repo.snapshot("status").unwrap();
6461
    assert!(!snap.changed && snap.statuses.is_empty());
6462
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6463
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6464
}
6465
6466
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
6467
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
6468
/// file is unchanged, and loading through the checkpoint equals a full load.
6469
#[test]
6470
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
6471
    hermetic();
6472
    let dir = tempfile::tempdir().unwrap();
6473
    let root = dir.path();
6474
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6475
    let long: String = (0..300)
6476
        .map(|i| format!("line {i} of a long file\n"))
6477
        .collect();
6478
    write(root, "long.txt", long.as_bytes());
6479
    write(root, "short.txt", b"short\n");
6480
    repo.commit("base", &[]).unwrap();
6481
    let (r1, _, _) = repo.checkpoint().unwrap();
6482
    let cp1 = crate::objects::Checkpoint::decode(
6483
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
6484
    )
6485
    .unwrap();
6486
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
6487
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
6488
6489
    // gc keeps the graph blob; fsck finds the checkpoint sound.
6490
    repo.gc(true).unwrap();
6491
    assert!(repo.store().has(&graphs1[0]));
6492
    let report = repo.fsck().unwrap();
6493
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
6494
6495
    // Loading through the checkpoint equals a full load.
6496
    write(root, "short.txt", b"short, edited\n");
6497
    repo.commit("edit the short file", &[]).unwrap();
6498
    let heads = repo.bookmark_heads().unwrap();
6499
    let fast = repo.load_state(&heads).unwrap();
6500
    let full = repo.load_state_full(&heads).unwrap();
6501
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
6502
6503
    // The next checkpoint shares the unchanged long file's graph.
6504
    let (r2, _, _) = repo.checkpoint().unwrap();
6505
    let cp2 = crate::objects::Checkpoint::decode(
6506
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
6507
    )
6508
    .unwrap();
6509
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
6510
6511
    // A shallow clone's bundle carries the graph blob with the checkpoint.
6512
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
6513
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
6514
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
6515
6516
    // A version 1 checkpoint written by an older oxy still loads.
6517
    let state = repo.load_state_full(&heads).unwrap();
6518
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
6519
    let cp_old = crate::objects::Checkpoint {
6520
        heads: cp2.heads.clone(),
6521
        count: cp2.count,
6522
        payload: old,
6523
    };
6524
    let r_old = repo
6525
        .store()
6526
        .put(ObjectType::Checkpoint, &cp_old.encode())
6527
        .unwrap();
6528
    repo.install_checkpoint("main", &r_old).unwrap();
6529
    assert_eq!(
6530
        repo.load_state(&heads).unwrap().checkpoint_payload(),
6531
        full.checkpoint_payload()
6532
    );
6533
    assert_eq!(repo.fsck().unwrap().errors(), 0);
6534
6535
    // A lost graph blob fails the load loudly rather than dropping the
6536
    // file, and fsck reports it (a fresh repository, objects still loose).
6537
    let dir2 = tempfile::tempdir().unwrap();
6538
    let root2 = dir2.path();
6539
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
6540
    write(root2, "long.txt", long.as_bytes());
6541
    repo2.commit("base", &[]).unwrap();
6542
    let (r, _, _) = repo2.checkpoint().unwrap();
6543
    let cp = crate::objects::Checkpoint::decode(
6544
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
6545
    )
6546
    .unwrap();
6547
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
6548
    repo2.store().remove_loose_for_test(&graph).unwrap();
6549
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
6550
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
6551
}
6552
6553
/// A new repository has not stored the user's identity yet (that happens
6554
/// at the first signed change); looking it up falls back to the key
6555
/// directory, and a file there that does not hash to the key is refused.
6556
#[test]
6557
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
6558
    hermetic();
6559
    let dir = tempfile::tempdir().unwrap();
6560
    let home = dir.path().join("home");
6561
    let mut first = Repo::init(&dir.path().join("a"))
6562
        .unwrap()
6563
        .with_home(home.clone());
6564
    let (key, _) = first
6565
        .create_identity("Ada", "[email protected]", IdentityScope::User)
6566
        .unwrap();
6567
    let fresh = Repo::init(&dir.path().join("b"))
6568
        .unwrap()
6569
        .with_home(home.clone());
6570
    assert!(!fresh.store().has(&key), "nothing stored yet");
6571
    let id = fresh.identity(&key).unwrap();
6572
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
6573
    // A key file that is not this identity is an error, not a wrong answer.
6574
    let keys = fresh.keys_dir.clone();
6575
    let (other, _) = first
6576
        .create_identity("Bob", "[email protected]", IdentityScope::User)
6577
        .unwrap();
6578
    fs::copy(
6579
        keys.join(format!("{}.identity", other.to_hex())),
6580
        keys.join(format!("{}.identity", key.to_hex())),
6581
    )
6582
    .unwrap();
6583
    assert!(fresh
6584
        .identity(&key)
6585
        .unwrap_err()
6586
        .to_string()
6587
        .contains("does not hold identity"));
6588
}
6589
6590
/// Status snapshots (spec §12.3): a text file whose stat matches the
6591
/// manifest, and whose base graph key is the one the manifest recorded it
6592
/// equal to, is neither read nor rendered; any edit, and any change to the
6593
/// file's graph in the base, brings it back.
6594
#[cfg(unix)]
6595
#[test]
6596
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
6597
    use std::os::unix::fs::PermissionsExt;
6598
    hermetic();
6599
    let dir = tempfile::tempdir().unwrap();
6600
    let root = dir.path();
6601
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6602
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
6603
        write(root, p, c.as_bytes());
6604
    }
6605
    repo.commit("base", &[]).unwrap();
6606
    let age = |p: &str| {
6607
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6608
        fs::File::options()
6609
            .write(true)
6610
            .open(root.join(p))
6611
            .unwrap()
6612
            .set_modified(old)
6613
            .unwrap();
6614
    };
6615
    let lock = |p: &str, mode: u32| {
6616
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
6617
    };
6618
    for p in ["a.txt", "b.txt", "d/c.txt"] {
6619
        age(p);
6620
    }
6621
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
6622
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6623
    assert!(
6624
        m.entries.values().all(|e| e.graph.is_some()),
6625
        "keys recorded"
6626
    );
6627
6628
    // Unreadable files prove they are not read; the status snapshot does
6629
    // not render them either, and its base lacks their graphs.
6630
    lock("a.txt", 0o000);
6631
    lock("b.txt", 0o000);
6632
    let snap = repo.snapshot_status("status").unwrap();
6633
    assert!(!snap.changed && snap.statuses.is_empty());
6634
    assert_eq!(
6635
        snap.base_snapshot
6636
            .unrendered
6637
            .iter()
6638
            .cloned()
6639
            .collect::<Vec<_>>(),
6640
        vec!["a.txt", "b.txt", "d/c.txt"]
6641
    );
6642
    assert!(!snap.base.is_full());
6643
    assert!(!snap.base_snapshot.is_conflicted());
6644
    // A full snapshot does not read them either, but renders everything.
6645
    let full = repo.snapshot("status").unwrap();
6646
    assert!(full.statuses.is_empty() && full.base.is_full());
6647
    assert!(full.base_snapshot.unrendered.is_empty());
6648
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
6649
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
6650
6651
    // An edit is seen; the file is rendered, the others still are not.
6652
    write(root, "d/c.txt", b"sea edited\n");
6653
    let snap = repo.snapshot_status("status").unwrap();
6654
    assert_eq!(
6655
        statuses(&snap),
6656
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
6657
    );
6658
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
6659
    // So is a mode change of an unread file.
6660
    lock("b.txt", 0o100);
6661
    assert_eq!(
6662
        statuses(&repo.snapshot_status("status").unwrap()),
6663
        vec![
6664
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
6665
            ("d/c.txt".to_string(), ChangeStatus::Modified)
6666
        ]
6667
    );
6668
    lock("b.txt", 0o000);
6669
6670
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
6671
    // stays unread, c.txt is read once and then skipped too.
6672
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
6673
        .unwrap();
6674
    age("d/c.txt");
6675
    let snap = repo.snapshot_status("status").unwrap();
6676
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
6677
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
6678
    lock("d/c.txt", 0o000);
6679
    let snap = repo.snapshot_status("status").unwrap();
6680
    assert!(snap.statuses.is_empty());
6681
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
6682
    for p in ["a.txt", "b.txt", "d/c.txt"] {
6683
        lock(p, 0o644);
6684
    }
6685
}
6686
6687
/// Attributes decide how a file compares with the base, so a changed
6688
/// `.oxyattributes` makes every text file be compared again.
6689
#[cfg(unix)]
6690
#[test]
6691
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
6692
    hermetic();
6693
    let dir = tempfile::tempdir().unwrap();
6694
    let root = dir.path();
6695
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6696
    write(root, "a.txt", b"crlf\r\n");
6697
    repo.commit("base", &[]).unwrap();
6698
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6699
    fs::File::options()
6700
        .write(true)
6701
        .open(root.join("a.txt"))
6702
        .unwrap()
6703
        .set_modified(old)
6704
        .unwrap();
6705
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6706
    assert!(repo
6707
        .snapshot_status("status")
6708
        .unwrap()
6709
        .base_snapshot
6710
        .unrendered
6711
        .contains("a.txt"));
6712
    // With eol=lf, a.txt as stored no longer equals the base.
6713
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
6714
    let snap = repo.snapshot_status("status").unwrap();
6715
    assert_eq!(
6716
        statuses(&snap),
6717
        vec![
6718
            (".oxyattributes".to_string(), ChangeStatus::Added),
6719
            ("a.txt".to_string(), ChangeStatus::Modified)
6720
        ]
6721
    );
6722
}
6723
6724
/// Bookmarks with `/` in their names: pushing records their
6725
/// attestations, and checkpoints are kept for them, beside `feature`
6726
/// itself.
6727
#[test]
6728
fn bookmarks_with_slashes_push_and_checkpoint() {
6729
    hermetic();
6730
    let dir = tempfile::tempdir().unwrap();
6731
    let root = dir.path();
6732
    let origin = Repo::init(&root.join("origin")).unwrap();
6733
    let url = root.join("origin").to_string_lossy().to_string();
6734
    let mut repo = Repo::clone(&url, &root.join("r"))
6735
        .unwrap()
6736
        .with_home(root.join("home"));
6737
    // With an identity, pushes carry reference attestations: the case
6738
    // that failed, since the attestation is a file named after the bookmark.
6739
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6740
        .unwrap();
6741
    let r = root.join("r");
6742
    write(&r, "a.txt", b"a\n");
6743
    let h_a = repo.commit("a", &[]).unwrap();
6744
    assert!(repo.push("origin", false).unwrap()[0].ok);
6745
    origin.refresh().unwrap();
6746
    repo.bookmark_create("feature", None).unwrap();
6747
    repo.bookmark_create("feature/x", None).unwrap();
6748
    repo.bookmark_switch("feature/x", false).unwrap();
6749
    write(&r, "b.txt", b"b\n");
6750
    let h_b = repo.commit("b", &[]).unwrap();
6751
    for name in ["feature", "feature/x"] {
6752
        let res = repo.push_bookmark("origin", name, false).unwrap();
6753
        origin.refresh().unwrap();
6754
        assert!(res[0].ok, "{name}: {res:?}");
6755
    }
6756
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
6757
    assert_eq!(
6758
        origin.resolve_heads("feature/x").unwrap(),
6759
        repo.resolve_heads("feature/x").unwrap()
6760
    );
6761
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
6762
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
6763
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
6764
6765
    // A checkpoint of feature/x is found again when loading its state.
6766
    let (cp, _, _) = repo.checkpoint().unwrap();
6767
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
6768
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
6769
    let heads = repo.resolve_heads("feature/x").unwrap();
6770
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
6771
}
6772
6773
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
6774
/// never the remote's own bookmark, and a bookmark created again later is
6775
/// accepted although the deletion's attestation stays the latest.
6776
#[test]
6777
fn bookmarks_are_deleted_on_a_remote() {
6778
    hermetic();
6779
    let dir = tempfile::tempdir().unwrap();
6780
    let root = dir.path();
6781
    let origin = Repo::init(&root.join("origin")).unwrap();
6782
    let url = root.join("origin").to_string_lossy().to_string();
6783
    let mut repo = Repo::clone(&url, &root.join("r"))
6784
        .unwrap()
6785
        .with_home(root.join("home"));
6786
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6787
        .unwrap();
6788
    let r = root.join("r");
6789
    write(&r, "a.txt", b"a\n");
6790
    repo.commit("a", &[]).unwrap();
6791
    assert!(repo.push("origin", false).unwrap()[0].ok);
6792
    origin.refresh().unwrap();
6793
    repo.bookmark_create("feature/x", None).unwrap();
6794
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
6795
    origin.refresh().unwrap();
6796
    assert!(origin.resolve_heads("feature/x").is_ok());
6797
6798
    let res = repo.push_delete("origin", "feature/x").unwrap();
6799
    origin.refresh().unwrap();
6800
    assert!(res[0].ok, "{res:?}");
6801
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
6802
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
6803
    assert!(
6804
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
6805
        "the deletion is attested"
6806
    );
6807
    assert!(
6808
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
6809
        "the local bookmark stays"
6810
    );
6811
    assert!(!repo
6812
        .view()
6813
        .unwrap()
6814
        .remotes
6815
        .get("origin")
6816
        .is_some_and(|m| m.contains_key("feature/x")));
6817
6818
    // Pushing it again creates it again, past the deletion's serial.
6819
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
6820
    origin.refresh().unwrap();
6821
    assert!(res[0].ok, "{res:?}");
6822
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
6823
6824
    // Nothing to delete, and never the remote's own bookmark.
6825
    assert!(repo.push_delete("origin", "nope").is_err());
6826
    let res = repo.push_delete("origin", "main").unwrap();
6827
    origin.refresh().unwrap();
6828
    assert!(
6829
        !res[0].ok && res[0].reason.contains("default bookmark"),
6830
        "{res:?}"
6831
    );
6832
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
6833
}
6834
6835
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
6836
/// when the target has the same versions of the files it touches, and is
6837
/// refused, untouched, when it has others.
6838
#[test]
6839
fn switching_bookmarks_carries_uncommitted_work() {
6840
    hermetic();
6841
    let dir = tempfile::tempdir().unwrap();
6842
    let root = dir.path();
6843
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6844
    write(root, "a.txt", b"a\n");
6845
    write(root, "b.txt", b"b\n");
6846
    write(root, "gone.txt", b"gone\n");
6847
    repo.commit("base", &[]).unwrap();
6848
    repo.bookmark_create("feature", None).unwrap();
6849
    // Started on main, belongs on feature: edit, add, remove.
6850
    write(root, "a.txt", b"a\nmore\n");
6851
    write(root, "new.txt", b"new\n");
6852
    fs::remove_file(root.join("gone.txt")).unwrap();
6853
    let (report, carried) = repo.bookmark_switch_carry("feature").unwrap();
6854
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
6855
    // oxygen#120: the new file was carried, not removed.
6856
    assert_eq!(
6857
        (report.removed, report.removed_paths.len()),
6858
        (0, 0),
6859
        "{report:?}"
6860
    );
6861
    assert_eq!(repo.config.bookmark, "feature");
6862
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
6863
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
6864
    assert!(!root.join("gone.txt").exists());
6865
    let snap = repo.snapshot("status").unwrap();
6866
    assert_eq!(
6867
        statuses(&snap),
6868
        vec![
6869
            ("a.txt".to_string(), ChangeStatus::Modified),
6870
            ("gone.txt".to_string(), ChangeStatus::Removed),
6871
            ("new.txt".to_string(), ChangeStatus::Added)
6872
        ]
6873
    );
6874
    repo.commit("the work", &[]).unwrap();
6875
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
6876
6877
    // main moves b.txt on; work on feature touching b.txt cannot follow.
6878
    repo.bookmark_switch("main", false).unwrap();
6879
    write(root, "b.txt", b"b on main\n");
6880
    repo.commit("b on main", &[]).unwrap();
6881
    repo.bookmark_switch("feature", false).unwrap();
6882
    write(root, "b.txt", b"b edited\n");
6883
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
6884
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
6885
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
6886
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
6887
}
6888
6889
/// Merging and checking out (feedback 3): a working copy without changes
6890
/// follows a merge whichever state it sat on; a refused checkout names
6891
/// what is in the way; `checkout --carry` takes the work along.
6892
#[test]
6893
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
6894
    hermetic();
6895
    let dir = tempfile::tempdir().unwrap();
6896
    let root = dir.path();
6897
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6898
    write(root, "a.txt", b"a\n");
6899
    let h1 = repo.commit("a", &[]).unwrap();
6900
    write(root, "b.txt", b"b\n");
6901
    repo.commit("b", &[]).unwrap();
6902
    repo.bookmark_create("feature", None).unwrap();
6903
    repo.bookmark_switch("feature", false).unwrap();
6904
    write(root, "c.txt", b"c\n");
6905
    repo.commit("c on feature", &[]).unwrap();
6906
    repo.bookmark_switch("main", false).unwrap();
6907
    // The working copy sits on an older state than main's heads.
6908
    repo.checkout(&[h1], false, "checkout").unwrap();
6909
    assert!(!root.join("b.txt").exists());
6910
    let m = repo.merge("feature").unwrap();
6911
    assert!(m.checked_out, "a clean working copy follows the merge");
6912
    for f in ["a.txt", "b.txt", "c.txt"] {
6913
        assert!(root.join(f).exists(), "{f}");
6914
    }
6915
6916
    // A refusal says which paths are in the way and what to do.
6917
    fs::remove_file(root.join("b.txt")).unwrap();
6918
    write(root, "a.txt", b"a edited\n");
6919
    let err = repo
6920
        .checkout(&[h1], false, "checkout")
6921
        .unwrap_err()
6922
        .to_string();
6923
    assert!(
6924
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
6925
        "{err}"
6926
    );
6927
    // --carry takes them along: h1 has a.txt as the base has it, and the
6928
    // removed b.txt is already as h1 has it (none), so that is no conflict
6929
    // either (oxygen#100).
6930
    let (_, carried) = repo
6931
        .checkout_carry(&[h1], "the first change", "checkout")
6932
        .unwrap();
6933
    assert_eq!(carried, vec!["a.txt"]);
6934
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
6935
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
6936
}
6937
6938
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
6939
/// user identity not stored in a new repository yet is fine while its
6940
/// secret key is there; an added subrepo is listed as not committed yet.
6941
#[test]
6942
fn a_new_repository_is_healthy_before_its_first_commit() {
6943
    hermetic();
6944
    let dir = tempfile::tempdir().unwrap();
6945
    let root = dir.path();
6946
    let home = root.join("home");
6947
    let mut first = Repo::init(&root.join("first"))
6948
        .unwrap()
6949
        .with_home(home.clone());
6950
    let (key, _) = first
6951
        .create_identity("Ada", "[email protected]", IdentityScope::User)
6952
        .unwrap();
6953
    let repo = Repo::init(&root.join("second"))
6954
        .unwrap()
6955
        .with_home(home.clone());
6956
    // Only the secret key: no identity object anywhere this repository sees.
6957
    let keys = repo.keys_dir.clone();
6958
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
6959
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
6960
    let r = repo.doctor(true);
6961
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
6962
    assert_eq!(id.health, Health::Ok, "{}", id.message);
6963
    assert!(id.message.contains("first signed change"), "{}", id.message);
6964
6965
    // A subrepo added and not committed yet is listed, pinned where it is.
6966
    let lib = root.join("lib");
6967
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
6968
    write(&lib, "x.txt", b"x\n");
6969
    l.commit("x", &[]).unwrap();
6970
    let second = root.join("second");
6971
    write(&second, "a.txt", b"a\n");
6972
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
6973
        .unwrap();
6974
    let subs = repo.subrepos().unwrap();
6975
    assert_eq!(subs.len(), 1);
6976
    assert_eq!(
6977
        (subs[0].path.as_str(), subs[0].committed),
6978
        ("deps/lib", false)
6979
    );
6980
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
6981
    repo.commit("add lib", &[]).unwrap();
6982
    let subs = repo.subrepos().unwrap();
6983
    assert!(subs[0].committed, "committed now");
6984
}
6985
6986
/// Commit, diff, hunks and discard use the partial snapshot: a file
6987
/// unchanged since the manifest is neither read nor rendered, and showing
6988
/// a change renders only what it edits, the same as from a full base.
6989
#[cfg(unix)]
6990
#[test]
6991
fn commits_and_diffs_leave_unchanged_files_alone() {
6992
    use std::os::unix::fs::PermissionsExt;
6993
    hermetic();
6994
    let dir = tempfile::tempdir().unwrap();
6995
    let root = dir.path();
6996
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6997
    write(root, "big.txt", b"lots\nof\nlines\n");
6998
    write(root, "a.txt", b"one\ntwo\n");
6999
    repo.commit("base", &[]).unwrap();
7000
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
7001
    for f in ["big.txt", "a.txt"] {
7002
        fs::File::options()
7003
            .write(true)
7004
            .open(root.join(f))
7005
            .unwrap()
7006
            .set_modified(old)
7007
            .unwrap();
7008
    }
7009
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
7010
    // big.txt cannot be read at all from here on.
7011
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
7012
7013
    write(root, "a.txt", b"one\nTWO\nthree\n");
7014
    let diff = repo.diff_files(None).unwrap();
7015
    assert_eq!(
7016
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
7017
        ["a.txt"]
7018
    );
7019
    let (_, hunks) = repo.hunks().unwrap();
7020
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
7021
    let h = repo.commit("edit a", &[]).unwrap();
7022
7023
    // Showing the change needs only a.txt's graph, and renders as a full base does.
7024
    let c = repo.store().get_change(&h).unwrap();
7025
    let full = repo.load_state(&c.deps).unwrap();
7026
    let want = render_change(&c, &full, &full.materialize());
7027
    assert_eq!(repo.describe_change(&h).unwrap(), want);
7028
    let (base, snap) = repo.change_base(&c).unwrap();
7029
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
7030
7031
    // Discarding works the same way.
7032
    write(root, "a.txt", b"scratch\n");
7033
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
7034
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
7035
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
7036
}
7037
7038
/// A replace conflict (spec §9.3) is settled by a change that writes one
7039
/// candidate, or new bytes, at the path when the caller names it; a plain
7040
/// snapshot of a checkout never settles it on its own.
7041
#[test]
7042
fn replace_conflicts_are_settled_when_asked() {
7043
    hermetic();
7044
    let dir = tempfile::tempdir().unwrap();
7045
    let root = dir.path();
7046
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7047
    let blob = |n: u8| {
7048
        let mut v = vec![0u8; 64];
7049
        v[1] = n;
7050
        v
7051
    };
7052
    write(root, "img.bin", &blob(1));
7053
    repo.commit("add img", &[]).unwrap();
7054
    repo.bookmark_create("other", None).unwrap();
7055
    write(root, "img.bin", &blob(2));
7056
    repo.commit("img two", &[]).unwrap();
7057
    repo.bookmark_switch("other", false).unwrap();
7058
    write(root, "img.bin", &blob(3));
7059
    repo.commit("img three", &[]).unwrap();
7060
    repo.bookmark_switch("main", false).unwrap();
7061
    repo.merge("other").unwrap();
7062
    let heads = repo.bookmark_heads().unwrap();
7063
    let merged = repo.load_state(&heads).unwrap().materialize();
7064
    assert!(
7065
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
7066
        "a replace conflict"
7067
    );
7068
    // A snapshot of the checkout records nothing.
7069
    assert!(repo
7070
        .snapshot("status")
7071
        .unwrap()
7072
        .statuses
7073
        .iter()
7074
        .all(|s| s.path != "img.bin"));
7075
7076
    // Keeping candidate 3 settles it.
7077
    let author = repo.author();
7078
    let edits = [FileEdit {
7079
        path: "img.bin".into(),
7080
        content: Some(blob(3)),
7081
    }];
7082
    let c = repo
7083
        .build_change(&heads, &edits, "keep three", author)
7084
        .unwrap();
7085
    assert_eq!(c.kind, ChangeKind::Resolution);
7086
    let mut st = repo.load_state(&heads).unwrap();
7087
    for d in &c.deps {
7088
        assert!(st.contains(d));
7089
    }
7090
    assert!(
7091
        heads.iter().all(|h| c.deps.contains(h)),
7092
        "depends on both contributors"
7093
    );
7094
    st.add(c).unwrap();
7095
    let after = st.materialize();
7096
    assert!(!after.is_conflicted());
7097
    assert_eq!(
7098
        after.files["img.bin"].content,
7099
        FileContent::Opaque {
7100
            blobs: vec![Repo::blob_ref(&blob(3))]
7101
        }
7102
    );
7103
7104
    // New bytes settle it too.
7105
    let edits = [FileEdit {
7106
        path: "img.bin".into(),
7107
        content: Some(blob(9)),
7108
    }];
7109
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
7110
    let mut st = repo.load_state(&heads).unwrap();
7111
    st.add(c).unwrap();
7112
    assert_eq!(
7113
        st.materialize().files["img.bin"].content,
7114
        FileContent::Opaque {
7115
            blobs: vec![Repo::blob_ref(&blob(9))]
7116
        }
7117
    );
7118
}
7119
7120
/// The history of a range of lines (spec §27): the changes that wrote
7121
/// or deleted its atoms, or deleted atoms from between them; edits outside
7122
/// the range and changes the range's lines survived are not in it.
7123
#[test]
7124
fn line_ranges_have_exact_histories() {
7125
    hermetic();
7126
    let dir = tempfile::tempdir().unwrap();
7127
    let root = dir.path();
7128
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
7129
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
7130
    let base = repo.commit("add f", &[]).unwrap();
7131
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
7132
    let outside = repo.commit("change the import", &[]).unwrap();
7133
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
7134
    let inside = repo.commit("edit a line of a", &[]).unwrap();
7135
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
7136
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
7137
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
7138
    let after = repo.commit("add b after a", &[]).unwrap();
7139
    let heads = repo.bookmark_heads().unwrap();
7140
7141
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
7142
    let hist: Vec<ChangeHash> = repo
7143
        .line_history(&heads, "f.rs", 2, 4)
7144
        .unwrap()
7145
        .iter()
7146
        .map(|e| e.hash)
7147
        .collect();
7148
    for (h, what) in [
7149
        (base, "wrote it"),
7150
        (inside, "edited a line"),
7151
        (deleted, "deleted a line from inside"),
7152
    ] {
7153
        assert!(hist.contains(&h), "{what}");
7154
    }
7155
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
7156
        assert!(!hist.contains(&h), "{what}");
7157
    }
7158
    assert_eq!(hist[0], deleted, "newest first");
7159
    // One line: only what touched it.
7160
    let one: Vec<ChangeHash> = repo
7161
        .line_history(&heads, "f.rs", 1, 1)
7162
        .unwrap()
7163
        .iter()
7164
        .map(|e| e.hash)
7165
        .collect();
7166
    assert!(one.contains(&outside) && !one.contains(&inside));
7167
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
7168
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
7169
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
7170
}
7171
7172
#[test]
7173
fn receipts_are_kept_with_their_state_and_verified() {
7174
    use crate::receipt::{Receipt, SignedReceipt};
7175
    hermetic();
7176
    let dir = tempfile::tempdir().unwrap();
7177
    let root = dir.path();
7178
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
7179
    write(root, "a.txt", b"1\n");
7180
    repo.commit("A", &[]).unwrap();
7181
    let heads = repo.bookmark_heads().unwrap();
7182
    let state = repo
7183
        .store()
7184
        .put_state(&StateObject::new(heads.clone()))
7185
        .unwrap();
7186
    let out = repo.store_blob(b"built\n").unwrap();
7187
    let receipt = Receipt {
7188
        job_name: "build".into(),
7189
        pipeline_hash: ObjectRef([1; 32]),
7190
        scope_tree_hash: ObjectRef([2; 32]),
7191
        inputs: vec![],
7192
        environment: ObjectRef([3; 32]),
7193
        outputs: vec![out],
7194
        exit_code: 0,
7195
        duration_ms: 42,
7196
    };
7197
    let sk = SecretKey::generate();
7198
    let runner = sk.identity("earth-1", "runner@earth", 1);
7199
    let sr = SignedReceipt::sign(
7200
        receipt.clone(),
7201
        repo.id().unwrap(),
7202
        state,
7203
        "demo#1",
7204
        &runner,
7205
        &sk,
7206
    );
7207
7208
    let r = repo.add_receipt(&sr).unwrap();
7209
    let found = repo.receipts(&heads).unwrap();
7210
    assert_eq!(found.len(), 1);
7211
    assert_eq!(found[0].attest, r);
7212
    assert_eq!(found[0].signed, sr);
7213
    assert!(found[0].problem.is_none() && !found[0].revoked);
7214
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
7215
7216
    // Another repository's receipt, or a forged one, is refused.
7217
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
7218
    assert!(repo
7219
        .add_receipt(&elsewhere)
7220
        .unwrap_err()
7221
        .to_string()
7222
        .contains("another repository"));
7223
    let mut forged = sr.clone();
7224
    forged.receipt.exit_code = 1;
7225
    assert!(repo
7226
        .add_receipt(&forged)
7227
        .unwrap_err()
7228
        .to_string()
7229
        .contains("does not verify"));
7230
7231
    // A receipt signed by a short-lived key keeps its certificate and the
7232
    // issuer's identity, and reads back with them (oxygenhub#241).
7233
    let hub_sk = SecretKey::generate();
7234
    let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
7235
    let job_sk = SecretKey::generate();
7236
    let job = job_sk.identity("job 2 test", "[email protected]", 1);
7237
    let mut test_receipt = receipt.clone();
7238
    test_receipt.job_name = "test".into();
7239
    let plain = SignedReceipt::sign(
7240
        test_receipt,
7241
        repo.id().unwrap(),
7242
        state,
7243
        "demo#2",
7244
        &job,
7245
        &job_sk,
7246
    );
7247
    let now = plain.attest.hlc.wall_ms;
7248
    let cert = crate::cert::SignedCertificate::sign(
7249
        crate::cert::Certificate {
7250
            key: job.clone(),
7251
            issuer: hub.hash(),
7252
            subject: "repo:andy/demo:bookmark:main".into(),
7253
            claims: vec![],
7254
            scope: crate::identity::Scope::SEAL,
7255
            not_before: now - 1_000,
7256
            expires: now + 600_000,
7257
            grant: None,
7258
        },
7259
        &hub,
7260
        &hub_sk,
7261
    );
7262
    let certified = plain.with_certificate(cert, hub.clone());
7263
    repo.add_receipt(&certified).unwrap();
7264
    let found = repo.receipts(&heads).unwrap();
7265
    let got = found
7266
        .iter()
7267
        .find(|i| i.signed.receipt.job_name == "test")
7268
        .unwrap();
7269
    assert_eq!(got.signed, certified);
7270
    assert!(got.problem.is_none(), "{:?}", got.problem);
7271
7272
    // gc keeps the receipts, their runners, the certificate and its issuer,
7273
    // and the output while the state lives.
7274
    repo.gc(true).unwrap();
7275
    let found = repo.receipts(&heads).unwrap();
7276
    assert_eq!(found.len(), 2);
7277
    let got = found
7278
        .iter()
7279
        .find(|i| i.signed.receipt.job_name == "test")
7280
        .unwrap();
7281
    assert_eq!(got.signed, certified, "the certificate survives gc");
7282
    assert!(got.problem.is_none());
7283
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
7284
    assert!(repo.fsck().unwrap().problems.is_empty());
7285
}
7286
7287
#[test]
7288
fn approvals_are_kept_with_their_state_and_survive_gc() {
7289
    hermetic();
7290
    let dir = tempfile::tempdir().unwrap();
7291
    let root = dir.path();
7292
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
7293
    write(root, "a.txt", b"1\n");
7294
    repo.commit("A", &[]).unwrap();
7295
    let heads = repo.bookmark_heads().unwrap();
7296
    let state = repo.store().put_state(&StateObject::new(heads)).unwrap();
7297
    let plan = repo.store_blob(b"the reviewed plan\n").unwrap();
7298
    let sk = SecretKey::generate();
7299
    let andy = sk.identity("Andy", "[email protected]", 1);
7300
    let statement = crate::approval::Statement {
7301
        repo: repo.id().unwrap(),
7302
        run: "https://hub.example/andy/infra/flow/8".into(),
7303
        job: "apply".into(),
7304
        job_hash: ObjectRef([1; 32]),
7305
        state,
7306
        inputs: vec![plan],
7307
        environment: "prod".into(),
7308
        approve: true,
7309
    };
7310
    let sa = crate::approval::SignedApproval::sign(&statement, &andy, &sk);
7311
    let r = repo.add_approval(&sa).unwrap();
7312
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
7313
    // Another repository's approval, or a changed one, is refused.
7314
    let elsewhere = crate::approval::SignedApproval::sign(
7315
        &crate::approval::Statement {
7316
            repo: [0; 16],
7317
            ..statement.clone()
7318
        },
7319
        &andy,
7320
        &sk,
7321
    );
7322
    assert!(repo
7323
        .add_approval(&elsewhere)
7324
        .unwrap_err()
7325
        .to_string()
7326
        .contains("another repository"));
7327
    let mut forged = sa.clone();
7328
    if let AttestBody::Approval { environment, .. } = &mut forged.attest.body {
7329
        *environment = "dev".into();
7330
    }
7331
    assert!(repo
7332
        .add_approval(&forged)
7333
        .unwrap_err()
7334
        .to_string()
7335
        .contains("does not verify"));
7336
    // gc keeps it, its signature and its signer while the state lives.
7337
    repo.gc(true).unwrap();
7338
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
7339
    assert_eq!(repo.store().get_attest(&r).unwrap(), sa.attest);
7340
    assert_eq!(repo.store().signatures(&r).unwrap(), sa.sigs);
7341
    assert!(repo.fsck().unwrap().problems.is_empty());
7342
}
7343
7344
#[test]
7345
fn status_leaves_an_unchanged_manifest_alone() {
7346
    hermetic();
7347
    let dir = tempfile::tempdir().unwrap();
7348
    let root = dir.path();
7349
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
7350
    write(root, "a.txt", b"1\n");
7351
    write(root, "b.txt", b"2\n");
7352
    repo.commit("A", &[]).unwrap();
7353
    // Files last touched well outside the racy window.
7354
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7355
    for f in ["a.txt", "b.txt"] {
7356
        fs::File::options()
7357
            .write(true)
7358
            .open(root.join(f))
7359
            .unwrap()
7360
            .set_modified(old)
7361
            .unwrap();
7362
    }
7363
    repo.snapshot_status("status").unwrap();
7364
    let path = repo.manifest_path();
7365
    let first = fs::read(&path).unwrap();
7366
    repo.snapshot_status("status").unwrap();
7367
    assert_eq!(
7368
        fs::read(&path).unwrap(),
7369
        first,
7370
        "an unchanged tree does not rewrite the manifest"
7371
    );
7372
    // A change rewrites it.
7373
    write(root, "a.txt", b"1\n2\n");
7374
    repo.snapshot_status("status").unwrap();
7375
    assert_ne!(fs::read(&path).unwrap(), first);
7376
}
7377
7378
#[test]
7379
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
7380
    hermetic();
7381
    let dir = tempfile::tempdir().unwrap();
7382
    let root = dir.path();
7383
    let origin_path = root.join("origin");
7384
    Repo::init(&origin_path).unwrap();
7385
    let origin_url = origin_path.to_string_lossy().to_string();
7386
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
7387
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
7388
    write(&root.join("a"), "big.txt", big.as_bytes());
7389
    write(&root.join("a"), "small.txt", b"small\n");
7390
    let h1 = a.commit("large", &[]).unwrap();
7391
    let (_, body) = a.store().get(&h1).unwrap();
7392
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
7393
    assert!(a.push("origin", false).unwrap()[0].ok);
7394
7395
    // A clone reads the text from the blobs that came with the change.
7396
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
7397
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
7398
    // An edit in the middle of the stored insert is an ordinary change.
7399
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
7400
    write(&root.join("b"), "big.txt", edited.as_bytes());
7401
    let h2 = b.commit("edit", &[]).unwrap();
7402
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
7403
    assert!(b.push("origin", false).unwrap()[0].ok);
7404
    assert!(a.pull("origin").unwrap().checked_out);
7405
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
7406
    assert_eq!(
7407
        a.fsck().unwrap().errors(),
7408
        0,
7409
        "{:?}",
7410
        a.fsck().unwrap().problems
7411
    );
7412
7413
    // With zero retention gc keeps the text blobs of every kept change.
7414
    let mut a = Repo::open(&root.join("a")).unwrap();
7415
    a.config.set("core.op-retention", "0").unwrap();
7416
    a.save_config().unwrap();
7417
    let a = Repo::open(&root.join("a")).unwrap();
7418
    a.gc(true).unwrap();
7419
    let a = Repo::open(&root.join("a")).unwrap();
7420
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
7421
    assert_eq!(
7422
        a.fsck().unwrap().errors(),
7423
        0,
7424
        "{:?}",
7425
        a.fsck().unwrap().problems
7426
    );
7427
    // And a clone of the packed repository reads them from its packs.
7428
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
7429
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
7430
    drop(c);
7431
}
7432
7433
#[test]
7434
fn operations_that_both_replace_a_working_copy_are_not_merged() {
7435
    hermetic();
7436
    let dir = tempfile::tempdir().unwrap();
7437
    let root = dir.path();
7438
    let repo = Repo::init(root).unwrap();
7439
    write(root, "a.txt", b"a\n");
7440
    let a = repo.commit("a", &[]).unwrap();
7441
    write(root, "b.txt", b"b\n");
7442
    repo.commit("b", &[]).unwrap();
7443
    let (x, op) = repo.head_op().unwrap();
7444
    let ws = *op.view.workspaces.keys().next().unwrap();
7445
    let mut one = op.view.clone();
7446
    one.workspaces.insert(ws, a);
7447
    let mut two = op.view.clone();
7448
    two.workspaces.insert(ws, ObjectRef([7; 32]));
7449
    let first = repo.record_op(&[x], "one", one).unwrap();
7450
    let e = repo.record_op(&[x], "two", two).unwrap_err();
7451
    assert!(
7452
        e.to_string()
7453
            .contains("changed this working copy at the same time"),
7454
        "{e}"
7455
    );
7456
    assert_eq!(
7457
        repo.head_op().unwrap().0,
7458
        first,
7459
        "the second is not recorded"
7460
    );
7461
}
7462
7463
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
7464
/// rewrote the working copy recorded the half-written files as edits, and
7465
/// its view replaced the switch's.
7466
#[test]
7467
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
7468
    hermetic();
7469
    let dir = tempfile::tempdir().unwrap();
7470
    let root = dir.path().to_path_buf();
7471
    let mut repo = Repo::init(&root).unwrap();
7472
    write(&root, "keep.txt", b"keep\n");
7473
    repo.commit("base", &[]).unwrap();
7474
    repo.bookmark_create("small", None).unwrap();
7475
    for i in 0..300 {
7476
        write(
7477
            &root,
7478
            &format!("many/f{i}.txt"),
7479
            format!("file {i}\n").as_bytes(),
7480
        );
7481
    }
7482
    repo.commit("many", &[]).unwrap();
7483
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
7484
    let watcher = {
7485
        let (root, stop) = (root.clone(), stop.clone());
7486
        std::thread::spawn(move || {
7487
            let r = Repo::open(&root).unwrap();
7488
            let mut ran = 0;
7489
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
7490
                if r.snapshot_status("oxy status").is_ok() {
7491
                    ran += 1;
7492
                }
7493
            }
7494
            ran
7495
        })
7496
    };
7497
    for i in 0..20 {
7498
        let to = if i % 2 == 0 { "small" } else { "main" };
7499
        repo.bookmark_switch(to, false).unwrap();
7500
    }
7501
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
7502
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
7503
    // Back on main, clean, with every file where main has it.
7504
    let repo = Repo::open(&root).unwrap();
7505
    let s = repo.snapshot_status("oxy status").unwrap();
7506
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
7507
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
7508
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
7509
    assert!(root.join("many/f299.txt").exists());
7510
}
7511
7512
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
7513
/// put a subrepo that was ahead of its pin back at the pin and moved the
7514
/// subrepo's own bookmark backwards.
7515
#[test]
7516
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
7517
    hermetic();
7518
    let dir = tempfile::tempdir().unwrap();
7519
    let root = dir.path();
7520
    Repo::init(&root.join("lib-origin")).unwrap();
7521
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7522
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
7523
    write(&root.join("lib"), "lib.txt", b"v1\n");
7524
    lib.commit("lib v1", &[]).unwrap();
7525
    assert!(lib.push("origin", false).unwrap()[0].ok);
7526
7527
    let app_dir = root.join("app");
7528
    let mut app = Repo::init(&app_dir).unwrap();
7529
    write(&app_dir, "main.txt", b"app\n");
7530
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7531
    app.commit("app with lib", &[]).unwrap();
7532
    app.bookmark_create("feature", None).unwrap();
7533
7534
    // New work in the subrepo, not yet pinned by the parent.
7535
    let nested_dir = app_dir.join("libs/lib");
7536
    let nested = Repo::open(&nested_dir).unwrap();
7537
    write(&nested_dir, "new.txt", b"new\n");
7538
    let l2 = nested.commit("lib: new file", &[]).unwrap();
7539
    drop(nested);
7540
7541
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
7542
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
7543
    let nested = Repo::open(&nested_dir).unwrap();
7544
    assert!(
7545
        nested.bookmark_heads().unwrap().contains(&l2),
7546
        "its bookmark kept its work"
7547
    );
7548
    assert!(nested_dir.join("new.txt").exists(), "and its files");
7549
    let s = app.snapshot("status").unwrap();
7550
    assert_eq!(
7551
        statuses(&s),
7552
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
7553
    );
7554
}
7555
7556
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
7557
/// moving `main` to a change this clone had pushed on another bookmark,
7558
/// the first `pull` said "Already up to date" while `main` was behind.
7559
#[test]
7560
fn pull_takes_a_remote_move_to_changes_already_here() {
7561
    hermetic();
7562
    let dir = tempfile::tempdir().unwrap();
7563
    let root = dir.path();
7564
    let origin_path = root.join("origin");
7565
    let origin = Repo::init(&origin_path).unwrap();
7566
    let url = origin_path.to_string_lossy().to_string();
7567
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
7568
    write(&root.join("b"), "base.txt", b"base\n");
7569
    b.commit("base", &[]).unwrap();
7570
    assert!(b.push("origin", false).unwrap()[0].ok);
7571
    origin.refresh().unwrap();
7572
7573
    // A feature bookmark with one change, pushed.
7574
    b.bookmark_create("feat", None).unwrap();
7575
    b.bookmark_switch("feat", false).unwrap();
7576
    write(&root.join("b"), "x.txt", b"x\n");
7577
    let x = b.commit("x", &[]).unwrap();
7578
    assert!(b.push("origin", false).unwrap()[0].ok);
7579
    origin.refresh().unwrap();
7580
    b.bookmark_switch("main", false).unwrap();
7581
7582
    // The remote lands it: its main moves to the feature's state.
7583
    let feat = origin
7584
        .store()
7585
        .get_state(&origin.view().unwrap().bookmarks["feat"])
7586
        .unwrap()
7587
        .heads;
7588
    origin.bookmark_set("main", &feat).unwrap();
7589
7590
    let r = b.pull("origin").unwrap();
7591
    assert!(r.changed, "{r:?}");
7592
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
7593
    let main = b
7594
        .bookmarks()
7595
        .unwrap()
7596
        .into_iter()
7597
        .find(|m| m.name == "main")
7598
        .unwrap();
7599
    assert_eq!(main.behind, Some(0), "{main:?}");
7600
}
7601
7602
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
7603
/// to one only the remote has makes a local bookmark from it; a pull moves
7604
/// every local bookmark the remote has too; a clone checks out the remote's
7605
/// default bookmark.
7606
#[test]
7607
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
7608
    hermetic();
7609
    let dir = tempfile::tempdir().unwrap();
7610
    let root = dir.path();
7611
    let origin_path = root.join("origin");
7612
    let mut origin = Repo::init(&origin_path).unwrap();
7613
    let url = origin_path.to_string_lossy().to_string();
7614
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
7615
    write(&root.join("a"), "base.txt", b"base\n");
7616
    a.commit("base", &[]).unwrap();
7617
    assert!(a.push("origin", false).unwrap()[0].ok);
7618
    a.bookmark_create("develop", None).unwrap();
7619
    a.bookmark_switch("develop", false).unwrap();
7620
    write(&root.join("a"), "base.txt", b"base\nd1\n");
7621
    let d1 = a.commit("d1", &[]).unwrap();
7622
    assert!(a.push("origin", false).unwrap()[0].ok);
7623
7624
    // A clone has main only; origin/develop is a name all the same.
7625
    let c_root = root.join("c");
7626
    let mut c = Repo::clone(&url, &c_root).unwrap();
7627
    assert_eq!(c.config.bookmark, "main");
7628
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
7629
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
7630
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
7631
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
7632
7633
    // Switching makes the local bookmark from origin's.
7634
    c.bookmark_switch("develop", false).unwrap();
7635
    assert_eq!(c.config.bookmark, "develop");
7636
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
7637
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
7638
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
7639
    assert!(c.bookmark_switch("nowhere", false).is_err());
7640
7641
    // Both bookmarks move on the remote; one pull takes both.
7642
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
7643
    let d2 = a.commit("d2", &[]).unwrap();
7644
    assert!(a.push("origin", false).unwrap()[0].ok);
7645
    a.bookmark_switch("main", false).unwrap();
7646
    write(&root.join("a"), "m.txt", b"m\n");
7647
    let m = a.commit("m", &[]).unwrap();
7648
    assert!(a.push("origin", false).unwrap()[0].ok);
7649
    // oxygen#117: a remote's bookmark merges without switching to it.
7650
    let f = Repo::clone(&url, &root.join("f")).unwrap();
7651
    assert!(!f.view().unwrap().bookmarks.contains_key("develop"));
7652
    let merged = f.merge("origin/develop").unwrap();
7653
    assert!(merged.changed, "{merged:?}");
7654
    assert!(
7655
        f.load_state_indexed(&f.bookmark_heads().unwrap())
7656
            .unwrap()
7657
            .contains(&d1),
7658
        "main holds develop's change"
7659
    );
7660
    assert!(f
7661
        .merge("origin/nowhere")
7662
        .unwrap_err()
7663
        .to_string()
7664
        .contains("no bookmark origin/nowhere"));
7665
    let r = c.pull("origin").unwrap();
7666
    assert!(r.changed && r.checked_out, "{r:?}");
7667
    assert_eq!(r.heads, vec![d2]);
7668
    assert_eq!(r.others, vec!["main".to_string()]);
7669
    assert!(c.resolve_heads("main").unwrap().contains(&m));
7670
    assert_eq!(
7671
        fs::read(c_root.join("base.txt")).unwrap(),
7672
        b"base\nd1\nd2\n"
7673
    );
7674
    let again = c.pull("origin").unwrap();
7675
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
7676
7677
    // A clone checks out the remote's default bookmark.
7678
    origin.config.set("workspace.bookmark", "develop").unwrap();
7679
    origin.save_config().unwrap();
7680
    let e = Repo::clone(&url, &root.join("e")).unwrap();
7681
    assert_eq!(e.config.bookmark, "develop");
7682
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
7683
    let reopened = Repo::open(&root.join("e")).unwrap();
7684
    assert_eq!(reopened.config.bookmark, "develop");
7685
    // REMOTE/NAME names the remote's bookmark to switch to.
7686
    let mut e = reopened;
7687
    e.bookmark_switch("origin/main", false).unwrap();
7688
    assert_eq!(e.config.bookmark, "main");
7689
    assert!(e.bookmark_heads().unwrap().contains(&m));
7690
}
7691
7692
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
7693
/// op restore goes back to an operation, files included, and undo takes
7694
/// the restore back whole; op revert undoes one operation alone; each
7695
/// operation's changes are described from the views.
7696
#[test]
7697
fn operations_can_be_read_restored_and_reverted() {
7698
    hermetic();
7699
    let dir = tempfile::tempdir().unwrap();
7700
    let root = dir.path();
7701
    let repo = Repo::init(root).unwrap();
7702
    write(root, "a.txt", b"a\n");
7703
    let first = repo.commit("first", &[]).unwrap();
7704
    write(root, "a.txt", b"a\nb\n");
7705
    let second = repo.commit("second", &[]).unwrap();
7706
    let at_second = repo.head_op().unwrap().0.to_hex();
7707
    repo.bookmark_create("keep", None).unwrap();
7708
    let created = repo.head_op().unwrap().0.to_hex();
7709
    write(root, "n.txt", b"n\n");
7710
    let third = repo.commit("third", &[]).unwrap();
7711
7712
    // What each operation changed.
7713
    let ops = repo.op_log().unwrap();
7714
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
7715
    assert!(
7716
        changes
7717
            .iter()
7718
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
7719
        "{changes:?}"
7720
    );
7721
    assert!(changes
7722
        .iter()
7723
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
7724
7725
    // Reading at an earlier operation.
7726
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
7727
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
7728
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
7729
    write(root, "z.txt", b"z\n");
7730
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
7731
    fs::remove_file(root.join("z.txt")).unwrap();
7732
    assert!(repo.resolve_op("zz").is_err());
7733
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
7734
7735
    // Restore goes back, files and all; undo takes it back whole.
7736
    repo.op_restore(&at_second, false).unwrap();
7737
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
7738
    assert!(!root.join("n.txt").exists());
7739
    repo.undo().unwrap();
7740
    let mut heads = repo.bookmark_heads().unwrap();
7741
    heads.sort();
7742
    let mut want = vec![second, third];
7743
    want.sort();
7744
    assert_eq!(heads, want);
7745
    assert!(
7746
        root.join("n.txt").exists(),
7747
        "the files came back with the undo"
7748
    );
7749
7750
    // Revert the bookmark's creation alone: the commit after it stays.
7751
    let r = repo.op_revert(&created).unwrap();
7752
    assert_eq!(r.reverted, vec!["keep".to_string()]);
7753
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
7754
    assert!(repo
7755
        .load_state(&repo.bookmark_heads().unwrap())
7756
        .unwrap()
7757
        .contains(&third));
7758
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
7759
    let _ = first;
7760
}
7761
7762
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
7763
/// from the status cache while every file is as the snapshot left it, and
7764
/// from a snapshot again as soon as one is not.
7765
#[test]
7766
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
7767
    hermetic();
7768
    let dir = tempfile::tempdir().unwrap();
7769
    let root = dir.path();
7770
    let repo = Repo::init(root).unwrap();
7771
    write(root, "a.txt", b"a\n");
7772
    write(root, "b.txt", b"b\n");
7773
    repo.commit("base", &[]).unwrap();
7774
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
7775
7776
    write(root, "a.txt", b"a\nmore\n");
7777
    assert_eq!(
7778
        repo.status_by_manifest().unwrap(),
7779
        None,
7780
        "no snapshot of the edit yet"
7781
    );
7782
    let snap = repo.snapshot_status("oxy status").unwrap();
7783
    assert_eq!(snap.statuses.len(), 1);
7784
    let cached = repo
7785
        .status_by_manifest()
7786
        .unwrap()
7787
        .expect("answered from the cache");
7788
    assert_eq!(cached.len(), 1);
7789
    assert_eq!(
7790
        (cached[0].path.as_str(), cached[0].status),
7791
        ("a.txt", ChangeStatus::Modified)
7792
    );
7793
7794
    // Any further change sends status back to a snapshot.
7795
    write(root, "a.txt", b"a\nmore\nand more\n");
7796
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
7797
    repo.snapshot_status("oxy status").unwrap();
7798
    assert!(repo.status_by_manifest().unwrap().is_some());
7799
    write(root, "new.txt", b"n\n");
7800
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
7801
    fs::remove_file(root.join("new.txt")).unwrap();
7802
    assert!(
7803
        repo.status_by_manifest().unwrap().is_some(),
7804
        "back as it was"
7805
    );
7806
    fs::remove_file(root.join("b.txt")).unwrap();
7807
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
7808
    write(root, "b.txt", b"b\n");
7809
7810
    // A commit leaves nothing uncommitted: clean again, no cache needed.
7811
    repo.snapshot_status("oxy status").unwrap();
7812
    repo.commit("more", &[]).unwrap();
7813
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
7814
}
7815
7816
/// oxygen#41: while the status cache holds, the working copy's diff is
7817
/// rendered from the stored working-copy change, and says exactly what a
7818
/// snapshot's diff says.
7819
#[test]
7820
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
7821
    hermetic();
7822
    let dir = tempfile::tempdir().unwrap();
7823
    let root = dir.path();
7824
    let repo = Repo::init(root).unwrap();
7825
    write(root, "a.txt", b"one\ntwo\nthree\n");
7826
    write(root, "gone.txt", b"bye\n");
7827
    repo.commit("base", &[]).unwrap();
7828
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
7829
    write(root, "new.txt", b"hello\n");
7830
    fs::remove_file(root.join("gone.txt")).unwrap();
7831
    let snap = repo.snapshot_status("oxy status").unwrap();
7832
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
7833
    assert!(
7834
        repo.status_by_manifest().unwrap().is_some(),
7835
        "the cache holds"
7836
    );
7837
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
7838
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
7839
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
7840
7841
    // Committed, nothing changes: the diff is empty without loading the
7842
    // base (oxygen#94), and the same as rendering it.
7843
    repo.commit("all", &[]).unwrap();
7844
    repo.snapshot_status("oxy status").unwrap();
7845
    assert!(repo.status_by_manifest().unwrap().is_some());
7846
    assert!(repo
7847
        .working_copy_with_base_unless_unchanged()
7848
        .unwrap()
7849
        .is_none());
7850
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
7851
    assert_eq!(render_change(&wc, &base, &snapshot), "");
7852
    assert!(repo.diff_files(None).unwrap().is_empty());
7853
}
7854
7855
/// oxygen#41: a manifest written from a walk keeps every directory's time;
7856
/// while none has moved, the check stats the tracked files without listing
7857
/// the tree, and a file added or removed anywhere moves its directory's
7858
/// time, so the tree is listed again.
7859
#[test]
7860
fn the_manifest_check_skips_listing_while_no_directory_changed() {
7861
    hermetic();
7862
    let dir = tempfile::tempdir().unwrap();
7863
    let root = dir.path();
7864
    let repo = Repo::init(root).unwrap();
7865
    write(root, "a.txt", b"a\n");
7866
    write(root, "sub/deep/b.txt", b"b\n");
7867
    repo.commit("base", &[]).unwrap();
7868
    // Out of the racy window: every file and directory a minute old.
7869
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7870
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
7871
        fs::File::open(root.join(p))
7872
            .unwrap()
7873
            .set_modified(old)
7874
            .unwrap();
7875
    }
7876
    repo.snapshot_status("oxy status").unwrap();
7877
    repo.write_manifest(false, false).unwrap();
7878
    let m = repo.read_manifest().unwrap().unwrap().2;
7879
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
7880
    assert_eq!(
7881
        repo.disk_differs_by_dirs(&m),
7882
        Some(false),
7883
        "no listing needed"
7884
    );
7885
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
7886
7887
    // A same-size edit with a new time: found by its stat.
7888
    write(root, "sub/deep/b.txt", b"c\n");
7889
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
7890
    write(root, "sub/deep/b.txt", b"b\n");
7891
    fs::File::open(root.join("sub/deep/b.txt"))
7892
        .unwrap()
7893
        .set_modified(old)
7894
        .unwrap();
7895
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
7896
7897
    // A new file moves its directory's time: the tree must be listed.
7898
    write(root, "sub/deep/new.txt", b"n\n");
7899
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
7900
    assert_eq!(repo.status_by_manifest().unwrap(), None);
7901
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
7902
    // A removed one too.
7903
    fs::remove_file(root.join("a.txt")).unwrap();
7904
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
7905
}
7906
7907
/// oxygen#41: a commit right after a status takes the snapshot the status
7908
/// left (the status cache holds) rather than walking again, and commits
7909
/// exactly what a snapshot would have.
7910
#[test]
7911
fn a_commit_after_a_status_uses_the_cached_snapshot() {
7912
    hermetic();
7913
    let dir = tempfile::tempdir().unwrap();
7914
    let root = dir.path();
7915
    let repo = Repo::init(root).unwrap();
7916
    write(root, "a.txt", b"a\nb\n");
7917
    write(root, ".oxyattributes", b"*.bin binary\n");
7918
    repo.commit("base", &[]).unwrap();
7919
    write(root, "a.txt", b"a\nB\n");
7920
    write(root, "new.txt", b"new\n");
7921
    let snap = repo.snapshot_status("oxy status").unwrap();
7922
    let cached = repo
7923
        .snapshot_from_cache()
7924
        .unwrap()
7925
        .expect("the cache holds");
7926
    assert_eq!(cached.wc_hash, snap.wc_hash);
7927
    assert_eq!(cached.statuses, snap.statuses);
7928
    assert!(
7929
        !cached.attributes.is_empty(),
7930
        "the .oxyattributes file was read"
7931
    );
7932
    let h = repo.commit("edit", &[]).unwrap();
7933
    let c = repo.store().get_change(&h).unwrap();
7934
    assert_eq!(
7935
        c.tree_ops.len() + c.edits.len(),
7936
        snap.wc.tree_ops.len() + snap.wc.edits.len()
7937
    );
7938
    assert_eq!(
7939
        repo.status_by_manifest().unwrap(),
7940
        Some(vec![]),
7941
        "clean after the commit"
7942
    );
7943
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
7944
}
7945
7946
/// oxygen#41: a clean check that verified racy entries restamps the
7947
/// manifest, so later checks can trust them, and a same-size rewrite
7948
/// straight afterwards is still found: entries within two seconds of the
7949
/// new time stay racy.
7950
#[test]
7951
fn a_verified_clean_check_restamps_the_manifest_safely() {
7952
    hermetic();
7953
    let dir = tempfile::tempdir().unwrap();
7954
    let root = dir.path();
7955
    let repo = Repo::init(root).unwrap();
7956
    write(root, "a.txt", b"one\n");
7957
    repo.commit("one", &[]).unwrap();
7958
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
7959
    assert!(repo.clean_by_manifest().unwrap());
7960
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
7961
    assert!(after > before, "restamped");
7962
    write(root, "a.txt", b"two\n");
7963
    assert!(
7964
        !repo.clean_by_manifest().unwrap(),
7965
        "a same-size rewrite is still seen"
7966
    );
7967
}
7968
7969
/// oxygen#35: a history-only state keeps no inserted text. It reads a
7970
/// stored insert's text blob only when it builds that file's graph, and
7971
/// builds the same graph a full load does.
7972
#[test]
7973
fn history_only_states_read_text_only_for_the_graphs_they_build() {
7974
    hermetic();
7975
    let dir = tempfile::tempdir().unwrap();
7976
    let root = dir.path();
7977
    let repo = Repo::init(root).unwrap();
7978
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
7979
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
7980
    write(root, "big.txt", big.as_bytes());
7981
    write(root, "other.txt", other.as_bytes());
7982
    let h = repo.commit("two large files", &[]).unwrap();
7983
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
7984
    let h2 = repo.commit("append", &[]).unwrap();
7985
7986
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
7987
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
7988
        FileContent::Text { bytes, .. } => bytes.clone(),
7989
        other => panic!("{other:?}"),
7990
    };
7991
    // Built on demand, every graph renders as the full load's.
7992
    let mut hist = repo.load_state_history(&[h2]).unwrap();
7993
    let big_node = full.files["big.txt"].node;
7994
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
7995
    repo.load_all_graphs(&mut hist).unwrap();
7996
    let rendered = hist.materialize();
7997
    for p in ["big.txt", "other.txt"] {
7998
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
7999
    }
8000
8001
    // Without other.txt's text blob, history still loads and big.txt still
8002
    // builds: nothing read the other text.
8003
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
8004
    assert_eq!(texts.len(), 2);
8005
    let content = |r: &ObjectRef| -> Vec<u8> {
8006
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
8007
        blob.chunks
8008
            .iter()
8009
            .flat_map(|c| repo.store().get(c).unwrap().1)
8010
            .collect()
8011
    };
8012
    let other_text = texts
8013
        .iter()
8014
        .filter_map(|t| match t {
8015
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
8016
            _ => None,
8017
        })
8018
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
8019
        .unwrap();
8020
    repo.store().remove_loose_for_test(&other_text).unwrap();
8021
    let mut hist = repo.load_state_history(&[h2]).unwrap();
8022
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
8023
    assert!(repo
8024
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
8025
        .is_err());
8026
}
8027
8028
/// oxygen#35: the first status after a commit read and rendered every
8029
/// file (79 s and more than 14 GB on the Linux tree), because the
8030
/// manifest had no graph keys for files the commit added.
8031
#[test]
8032
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
8033
    use std::os::unix::fs::PermissionsExt;
8034
    hermetic();
8035
    let dir = tempfile::tempdir().unwrap();
8036
    let root = dir.path();
8037
    let repo = Repo::init(root).unwrap();
8038
    let files = ["a.txt", "b.txt", "d/c.txt"];
8039
    for p in files {
8040
        write(root, p, format!("{p}\n").as_bytes());
8041
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
8042
        fs::File::options()
8043
            .write(true)
8044
            .open(root.join(p))
8045
            .unwrap()
8046
            .set_modified(old)
8047
            .unwrap();
8048
    }
8049
    repo.commit("added", &[]).unwrap();
8050
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
8051
    assert!(
8052
        m.entries.values().all(|e| e.graph.is_some()),
8053
        "keys recorded at commit"
8054
    );
8055
    // Unreadable files prove the next status reads none of them.
8056
    for p in files {
8057
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
8058
    }
8059
    let snap = repo.snapshot_status("status").unwrap();
8060
    for p in files {
8061
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
8062
    }
8063
    assert!(!snap.changed && snap.statuses.is_empty());
8064
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
8065
}
8066
8067
/// oxygen#35: a checkout reads, renders and writes only the files whose
8068
/// graphs differ, and renders the rest a batch at a time.
8069
#[test]
8070
fn checkout_touches_only_what_differs_and_renders_in_batches() {
8071
    use std::os::unix::fs::PermissionsExt;
8072
    hermetic();
8073
    let dir = tempfile::tempdir().unwrap();
8074
    let root = dir.path();
8075
    let origin = root.join("origin");
8076
    let mut repo = Repo::init(&origin).unwrap();
8077
    // More files than one batch holds.
8078
    let n = 2100;
8079
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
8080
    for i in 0..n {
8081
        let p = format!("f/{i:04}.txt");
8082
        write(&origin, &p, format!("file {i}\n").as_bytes());
8083
        fs::File::options()
8084
            .write(true)
8085
            .open(origin.join(&p))
8086
            .unwrap()
8087
            .set_modified(old)
8088
            .unwrap();
8089
    }
8090
    repo.commit("many", &[]).unwrap();
8091
    repo.bookmark_create("feature", None).unwrap();
8092
    repo.bookmark_switch("feature", false).unwrap();
8093
    write(&origin, "f/0007.txt", b"changed\n");
8094
    repo.commit("one change", &[]).unwrap();
8095
8096
    // Switching back to main must not read the unchanged files.
8097
    for i in 0..n {
8098
        if i != 7 {
8099
            let p = origin.join(format!("f/{i:04}.txt"));
8100
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
8101
        }
8102
    }
8103
    let r = repo.bookmark_switch("main", false).unwrap();
8104
    for i in 0..n {
8105
        let p = origin.join(format!("f/{i:04}.txt"));
8106
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
8107
    }
8108
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
8109
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
8110
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
8111
8112
    // A clone renders every file, across batches.
8113
    let c = root.join("clone");
8114
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
8115
    for i in [0, 2047, 2048, n - 1] {
8116
        assert_eq!(
8117
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
8118
            format!("file {i}\n").as_bytes()
8119
        );
8120
    }
8121
    let cloned = Repo::open(&c).unwrap();
8122
    assert!(cloned
8123
        .snapshot_status("status")
8124
        .unwrap()
8125
        .statuses
8126
        .is_empty());
8127
}
8128
8129
/// A file written just before the manifest (inside the racy window) is
8130
/// checked by its hash: trusted when equal, caught when edited in place
8131
/// with the same size and time.
8132
#[test]
8133
fn a_racy_manifest_entry_is_checked_by_hash() {
8134
    hermetic();
8135
    let dir = tempfile::tempdir().unwrap();
8136
    let root = dir.path();
8137
    let repo = Repo::init(root).unwrap();
8138
    write(root, "a.txt", b"one\n");
8139
    repo.commit("fresh", &[]).unwrap();
8140
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
8141
    let t = fs::metadata(root.join("a.txt"))
8142
        .unwrap()
8143
        .modified()
8144
        .unwrap();
8145
    write(root, "a.txt", b"two\n");
8146
    fs::File::options()
8147
        .write(true)
8148
        .open(root.join("a.txt"))
8149
        .unwrap()
8150
        .set_modified(t)
8151
        .unwrap();
8152
    assert!(
8153
        !repo.clean_by_manifest().unwrap(),
8154
        "same size and time, other bytes"
8155
    );
8156
    assert_eq!(
8157
        statuses(&repo.snapshot_status("status").unwrap()),
8158
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
8159
    );
8160
}
8161
8162
/// A fetch on one machine moves changes as stored, text blobs among the
8163
/// objects; a change whose text blob did not come is refused, not stored.
8164
#[test]
8165
fn a_raw_bundle_without_a_changes_text_is_refused() {
8166
    hermetic();
8167
    let dir = tempfile::tempdir().unwrap();
8168
    let root = dir.path();
8169
    let a = Repo::init(&root.join("a")).unwrap();
8170
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
8171
    write(&root.join("a"), "big.txt", big.as_bytes());
8172
    let h = a.commit("big", &[]).unwrap();
8173
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
8174
    assert_eq!(bundle.raw_changes.len(), 1);
8175
    assert!(bundle.changes.is_empty());
8176
    let b = Repo::init(&root.join("b")).unwrap();
8177
    let mut without = bundle.clone();
8178
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
8179
    let e = b.import_bundle(&without, false).unwrap_err();
8180
    assert!(e.to_string().contains("came without its text blob"), "{e}");
8181
    assert!(!b.store().has(&h));
8182
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
8183
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
8184
}
8185
8186
/// oxygen#30 (vscode): a directory deleted in one line of history and made
8187
/// again was a second node for one Git path, so a file moved into it on
8188
/// another line, where the first node still stood, ended up in two places.
8189
/// An import now brings the directory back rather than make a new one.
8190
#[test]
8191
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
8192
    hermetic();
8193
    if std::process::Command::new("git")
8194
        .arg("--version")
8195
        .output()
8196
        .is_err()
8197
    {
8198
        eprintln!("git not installed; skipping");
8199
        return;
8200
    }
8201
    let dir = tempfile::tempdir().unwrap();
8202
    let root = dir.path();
8203
    let g = root.join("src.git");
8204
    fs::create_dir_all(&g).unwrap();
8205
    let git = |args: &[&str]| -> String {
8206
        let out = std::process::Command::new("git")
8207
            .arg("-C")
8208
            .arg(&g)
8209
            .args([
8210
                "-c",
8211
                "user.name=Grace",
8212
                "-c",
8213
                "[email protected]",
8214
                "-c",
8215
                "commit.gpgsign=false",
8216
            ])
8217
            .args(args)
8218
            .output()
8219
            .unwrap();
8220
        assert!(
8221
            out.status.success(),
8222
            "git {args:?}: {}",
8223
            String::from_utf8_lossy(&out.stderr)
8224
        );
8225
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8226
    };
8227
    git(&["init", "-q", "-b", "main"]);
8228
    write(&g, "d/a.txt", b"a\n");
8229
    write(&g, "c/x.txt", b"x\n");
8230
    git(&["add", "."]);
8231
    git(&["commit", "-qm", "base"]);
8232
    // One line: move x into d while d still stands.
8233
    git(&["checkout", "-qb", "side"]);
8234
    git(&["mv", "c/x.txt", "d/x.txt"]);
8235
    git(&["commit", "-qm", "x into d"]);
8236
    // The other: d goes, comes back, and x moves into it too.
8237
    git(&["checkout", "-q", "main"]);
8238
    git(&["rm", "-q", "d/a.txt"]);
8239
    git(&["commit", "-qm", "d goes"]);
8240
    write(&g, "d/b.txt", b"b\n");
8241
    git(&["add", "."]);
8242
    git(&["commit", "-qm", "d comes back"]);
8243
    git(&["mv", "c/x.txt", "d/x.txt"]);
8244
    git(&["commit", "-qm", "x into d again"]);
8245
    git(&["merge", "-q", "--no-edit", "side"]);
8246
8247
    let repo = Repo::init(&root.join("o")).unwrap();
8248
    repo.import_git(&g, "main").unwrap();
8249
    let v = repo.verify_git_import(&g, "main").unwrap();
8250
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8251
    let st = repo
8252
        .load_state_history(&repo.bookmark_heads().unwrap())
8253
        .unwrap();
8254
    let view = st.tree().view();
8255
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8256
    // The directory is the one the first commit made.
8257
    // Commits made in one second tie on time: find the first by its message.
8258
    let first = repo
8259
        .log()
8260
        .unwrap()
8261
        .into_iter()
8262
        .find(|e| e.change.message.starts_with("base"))
8263
        .unwrap();
8264
    let base = repo
8265
        .load_state_history(&[first.hash])
8266
        .unwrap()
8267
        .tree()
8268
        .view();
8269
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
8270
}
8271
8272
/// oxygen#30, the rest: a placement left under a directory another line
8273
/// removed is out of sight, so no diff reaches it; the merge that settles
8274
/// where the file is retires it.
8275
#[test]
8276
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
8277
    hermetic();
8278
    if std::process::Command::new("git")
8279
        .arg("--version")
8280
        .output()
8281
        .is_err()
8282
    {
8283
        eprintln!("git not installed; skipping");
8284
        return;
8285
    }
8286
    let dir = tempfile::tempdir().unwrap();
8287
    let root = dir.path();
8288
    let g = root.join("src.git");
8289
    fs::create_dir_all(&g).unwrap();
8290
    let run = |args: &[&str]| {
8291
        std::process::Command::new("git")
8292
            .arg("-C")
8293
            .arg(&g)
8294
            .args([
8295
                "-c",
8296
                "user.name=Grace",
8297
                "-c",
8298
                "[email protected]",
8299
                "-c",
8300
                "commit.gpgsign=false",
8301
            ])
8302
            .args(args)
8303
            .output()
8304
            .unwrap()
8305
    };
8306
    let git = |args: &[&str]| {
8307
        let out = run(args);
8308
        assert!(
8309
            out.status.success(),
8310
            "git {args:?}: {}",
8311
            String::from_utf8_lossy(&out.stderr)
8312
        );
8313
    };
8314
    git(&["init", "-q", "-b", "main"]);
8315
    write(&g, "c/x.txt", b"x\n");
8316
    write(&g, "keep.txt", b"k\n");
8317
    git(&["add", "."]);
8318
    git(&["commit", "-qm", "base"]);
8319
    // One line renames the file within c; the other moves it out of c,
8320
    // which goes.
8321
    git(&["checkout", "-qb", "side"]);
8322
    git(&["mv", "c/x.txt", "c/y.txt"]);
8323
    git(&["commit", "-qm", "rename within c"]);
8324
    git(&["checkout", "-q", "main"]);
8325
    fs::create_dir_all(g.join("n")).unwrap();
8326
    git(&["mv", "c/x.txt", "n/x.txt"]);
8327
    git(&["commit", "-qm", "move out of c"]);
8328
    // Git cannot merge the two renames; the merge keeps n/x.txt.
8329
    let _ = run(&["merge", "-q", "side"]);
8330
    let _ = run(&[
8331
        "rm",
8332
        "-q",
8333
        "--cached",
8334
        "--ignore-unmatch",
8335
        "c/y.txt",
8336
        "c/x.txt",
8337
    ]);
8338
    let _ = std::fs::remove_dir_all(g.join("c"));
8339
    write(&g, "n/x.txt", b"x\n");
8340
    git(&["add", "-A"]);
8341
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
8342
8343
    let repo = Repo::init(&root.join("o")).unwrap();
8344
    repo.import_git(&g, "main").unwrap();
8345
    let v = repo.verify_git_import(&g, "main").unwrap();
8346
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8347
    let st = repo
8348
        .load_state_history(&repo.bookmark_heads().unwrap())
8349
        .unwrap();
8350
    let view = st.tree().view();
8351
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8352
    assert!(view.entries.contains_key("n/x.txt"));
8353
}
8354
8355
/// oxygen#30, orphans: a file added on one line into a directory the other
8356
/// line removed is placed where the tree cannot show it; Git's merge keeps
8357
/// the file, and the import's merge leaves exactly one of it.
8358
#[test]
8359
fn git_import_merge_leaves_no_orphan_behind() {
8360
    hermetic();
8361
    if std::process::Command::new("git")
8362
        .arg("--version")
8363
        .output()
8364
        .is_err()
8365
    {
8366
        eprintln!("git not installed; skipping");
8367
        return;
8368
    }
8369
    let dir = tempfile::tempdir().unwrap();
8370
    let root = dir.path();
8371
    let g = root.join("src.git");
8372
    fs::create_dir_all(&g).unwrap();
8373
    let git = |args: &[&str]| {
8374
        let out = std::process::Command::new("git")
8375
            .arg("-C")
8376
            .arg(&g)
8377
            .args([
8378
                "-c",
8379
                "user.name=Grace",
8380
                "-c",
8381
                "[email protected]",
8382
                "-c",
8383
                "commit.gpgsign=false",
8384
            ])
8385
            .args(args)
8386
            .output()
8387
            .unwrap();
8388
        assert!(
8389
            out.status.success(),
8390
            "git {args:?}: {}",
8391
            String::from_utf8_lossy(&out.stderr)
8392
        );
8393
    };
8394
    git(&["init", "-q", "-b", "main"]);
8395
    write(&g, "d/f.txt", b"f\n");
8396
    write(&g, "keep.txt", b"k\n");
8397
    git(&["add", "."]);
8398
    git(&["commit", "-qm", "base"]);
8399
    git(&["checkout", "-qb", "side"]);
8400
    write(&g, "d/new.txt", b"new\n");
8401
    git(&["add", "."]);
8402
    git(&["commit", "-qm", "add into d"]);
8403
    git(&["checkout", "-q", "main"]);
8404
    git(&["rm", "-q", "d/f.txt"]);
8405
    git(&["commit", "-qm", "d goes"]);
8406
    git(&["merge", "-q", "--no-edit", "side"]);
8407
8408
    let repo = Repo::init(&root.join("o")).unwrap();
8409
    repo.import_git(&g, "main").unwrap();
8410
    let v = repo.verify_git_import(&g, "main").unwrap();
8411
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8412
    let st = repo
8413
        .load_state_history(&repo.bookmark_heads().unwrap())
8414
        .unwrap();
8415
    let view = st.tree().view();
8416
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8417
    assert!(view.entries.contains_key("d/new.txt"));
8418
}
8419
8420
/// fsck checks a change's text as the blobs it is stored in, without
8421
/// decoding it: a missing text blob is an error named for the change.
8422
#[test]
8423
fn fsck_names_a_missing_text_blob() {
8424
    hermetic();
8425
    let dir = tempfile::tempdir().unwrap();
8426
    let root = dir.path();
8427
    let repo = Repo::init(root).unwrap();
8428
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
8429
    write(root, "big.txt", big.as_bytes());
8430
    let h = repo.commit("big", &[]).unwrap();
8431
    assert_eq!(repo.fsck().unwrap().errors(), 0);
8432
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
8433
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
8434
        panic!("a stored text")
8435
    };
8436
    repo.store().remove_loose_for_test(&b).unwrap();
8437
    let rep = repo.fsck().unwrap();
8438
    assert!(rep.errors() > 0);
8439
    assert!(
8440
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
8441
        "{:?}",
8442
        rep.problems
8443
    );
8444
}
8445
8446
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
8447
/// reached with that remote's token and CA (a private subrepo then clones
8448
/// for anyone who can read the parent); another hub gets none of them.
8449
#[test]
8450
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
8451
    hermetic();
8452
    let dir = tempfile::tempdir().unwrap();
8453
    let mut repo = Repo::init(dir.path()).unwrap();
8454
    repo.config
8455
        .set(
8456
            "remote.origin.url",
8457
            "https://Hub.example:7343/doomsdayone/metalgear",
8458
        )
8459
        .unwrap();
8460
    repo.config.set("remote.origin.token", "secret").unwrap();
8461
    repo.config
8462
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
8463
        .unwrap();
8464
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
8465
    assert_eq!(same.token.as_deref(), Some("secret"));
8466
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
8467
    for other in [
8468
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
8469
        "https://hub.example/doomsdayone/rstar-api",
8470
        "http://hub.example:7343/doomsdayone/rstar-api",
8471
    ] {
8472
        let o = repo.credentials_for(other);
8473
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
8474
    }
8475
}
8476
8477
/// oxygen#47: a remote with no token of its own uses the user's credential
8478
/// store for its hub, and a nested checkout finds its parent's remote
8479
/// token there instead of keeping a copy.
8480
#[test]
8481
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
8482
    hermetic();
8483
    let home = tempfile::tempdir().unwrap();
8484
    let dir = tempfile::tempdir().unwrap();
8485
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
8486
    parent
8487
        .config
8488
        .set("remote.origin.url", "https://hub.example/o/parent")
8489
        .unwrap();
8490
    parent.save_config().unwrap();
8491
    assert_eq!(parent.remote_options("origin").token, None);
8492
    crate::credentials::Credentials::at(home.path())
8493
        .save("https://hub.example", "stored", Some("andy"), None)
8494
        .unwrap();
8495
    assert_eq!(
8496
        parent.remote_options("origin").token.as_deref(),
8497
        Some("stored")
8498
    );
8499
8500
    let empty_home = tempfile::tempdir().unwrap();
8501
    let nested = dir.path().join("deps").join("child");
8502
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
8503
    child
8504
        .config
8505
        .set("remote.origin.url", "https://hub.example/o/child")
8506
        .unwrap();
8507
    child.save_config().unwrap();
8508
    assert_eq!(child.remote_options("origin").token, None);
8509
    parent
8510
        .config
8511
        .set("remote.origin.token", "checkout")
8512
        .unwrap();
8513
    parent.save_config().unwrap();
8514
    assert_eq!(
8515
        child.remote_options("origin").token.as_deref(),
8516
        Some("checkout")
8517
    );
8518
    // Another hub's checkout token is not borrowed.
8519
    child
8520
        .config
8521
        .set("remote.origin.url", "https://other.example/o/child")
8522
        .unwrap();
8523
    assert_eq!(child.remote_options("origin").token, None);
8524
}
8525
8526
#[test]
8527
fn the_metadata_cache_survives_a_torn_tail() {
8528
    hermetic();
8529
    let dir = tempfile::tempdir().unwrap();
8530
    let root = dir.path();
8531
    let repo = Repo::init(root).unwrap();
8532
    write(root, "a.txt", b"1\n");
8533
    let h = repo.commit("first", &[]).unwrap();
8534
    let meta = repo.store().get_change_meta(&h).unwrap();
8535
    let cache = repo.store().dir().join("metas");
8536
    let len = fs::metadata(&cache).unwrap().len();
8537
    assert!(len > 0, "a change read is cached");
8538
    // A torn record at the end: the cache reads up to it and cuts it off.
8539
    fs::OpenOptions::new()
8540
        .append(true)
8541
        .open(&cache)
8542
        .unwrap()
8543
        .write_all(&[7; 20])
8544
        .unwrap();
8545
    let again = Repo::open(root).unwrap();
8546
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
8547
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
8548
}
8549
8550
#[test]
8551
fn a_manifest_that_does_not_check_reads_as_none() {
8552
    hermetic();
8553
    let dir = tempfile::tempdir().unwrap();
8554
    let root = dir.path();
8555
    let repo = Repo::init(root).unwrap();
8556
    write(root, "a.txt", b"1\n");
8557
    repo.commit("first", &[]).unwrap();
8558
    let path = repo.manifest_path();
8559
    let mut bytes = fs::read(&path).unwrap();
8560
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
8561
    let last = bytes.len() - 1;
8562
    bytes[last] ^= 1;
8563
    fs::write(&path, &bytes).unwrap();
8564
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
8565
    // The next status reads the files and writes it again.
8566
    let again = Repo::open(root).unwrap();
8567
    assert!(!again.snapshot("status").unwrap().changed);
8568
    assert!(again.read_manifest().unwrap().is_some());
8569
}
8570
8571
#[test]
8572
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
8573
    hermetic();
8574
    let dir = tempfile::tempdir().unwrap();
8575
    let root = dir.path();
8576
    let repo = Repo::init(root).unwrap();
8577
    write(root, "a.txt", b"1\n");
8578
    write(root, "b.txt", b"2\n");
8579
    // b.txt outside the racy window, so snapshots take it as unchanged.
8580
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
8581
    fs::File::options()
8582
        .write(true)
8583
        .open(root.join("b.txt"))
8584
        .unwrap()
8585
        .set_modified(old)
8586
        .unwrap();
8587
    repo.commit("first", &[]).unwrap();
8588
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
8589
    repo.snapshot_status("status").unwrap();
8590
    write(root, "a.txt", b"1\n2\n");
8591
    repo.commit("second", &[]).unwrap();
8592
    assert!(
8593
        repo.clean_by_manifest().unwrap(),
8594
        "after a commit of one file"
8595
    );
8596
    // Edited, seen by a status, edited again, then committed: the status
8597
    // left the first edit's stat, which the commit must not keep.
8598
    write(root, "a.txt", b"1\n2\n3\n");
8599
    repo.snapshot_status("status").unwrap();
8600
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
8601
    repo.commit("third", &[]).unwrap();
8602
    assert!(
8603
        repo.clean_by_manifest().unwrap(),
8604
        "after an edit a status saw"
8605
    );
8606
}
8607
8608
#[test]
8609
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
8610
    hermetic();
8611
    let dir = tempfile::tempdir().unwrap();
8612
    let root = dir.path();
8613
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
8614
    write(root, "a.txt", b"1\n2\n");
8615
    let a = repo.commit("A", &[]).unwrap();
8616
    repo.bookmark_create("develop", Some(&[a])).unwrap();
8617
    write(root, "a.txt", b"1\nX\n");
8618
    let c = repo.commit("C: 2 to X", &[]).unwrap();
8619
    repo.bookmark_switch("develop", false).unwrap();
8620
    write(root, "a.txt", b"1\nY\n");
8621
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
8622
    repo.bookmark_switch("main", false).unwrap();
8623
8624
    let err = repo.rebase(&c, &[d]).unwrap_err();
8625
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
8626
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
8627
    assert!(r.changed && r.checked_out);
8628
    let snap = repo.snapshot_status("status").unwrap();
8629
    assert!(
8630
        snap.base_snapshot.is_conflicted(),
8631
        "the conflict is in the working copy"
8632
    );
8633
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
8634
    assert!(text.contains('X') && text.contains('Y'), "{text}");
8635
8636
    write(root, "a.txt", b"1\nXY\n");
8637
    repo.commit("Resolve", &[]).unwrap();
8638
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
8639
    assert!(st.contains(&c) && st.contains(&d));
8640
    let files = st.materialize().files;
8641
    assert!(!files["a.txt"].is_conflicted());
8642
    assert!(
8643
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
8644
    );
8645
8646
    // A change the current bookmark does not hold is refused.
8647
    repo.bookmark_switch("develop", false).unwrap();
8648
    write(root, "b.txt", b"b\n");
8649
    let e = repo.commit("E", &[]).unwrap();
8650
    repo.bookmark_switch("main", false).unwrap();
8651
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
8652
    assert!(
8653
        err.to_string().contains("not on the current bookmark"),
8654
        "{err}"
8655
    );
8656
}
8657
8658
#[test]
8659
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
8660
    hermetic();
8661
    let dir = tempfile::tempdir().unwrap();
8662
    let root = dir.path();
8663
    let repo = Repo::init(root).unwrap();
8664
    write(root, "a.txt", b"a\n");
8665
    write(root, "kept.log", b"tracked\n");
8666
    repo.commit("first", &[]).unwrap();
8667
    write(root, "build.log", b"made\n");
8668
    let snap = repo.snapshot_status("status").unwrap();
8669
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
8670
    // A rule written afterwards leaves the added file out again, while the
8671
    // committed one stays tracked.
8672
    write(root, ".gitignore", b"*.log\n");
8673
    let snap = repo.snapshot_status("status").unwrap();
8674
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
8675
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
8676
    write(root, "kept.log", b"tracked, edited\n");
8677
    let snap = repo.snapshot_status("status").unwrap();
8678
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
8679
}
8680
8681
#[test]
8682
fn shed_graphs_come_back_the_same() {
8683
    hermetic();
8684
    let dir = tempfile::tempdir().unwrap();
8685
    let root = dir.path();
8686
    let repo = Repo::init(root).unwrap();
8687
    write(root, "a.txt", b"1\n2\n3\n");
8688
    write(root, "b.txt", b"x\n");
8689
    repo.commit("first", &[]).unwrap();
8690
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
8691
    repo.commit("second", &[]).unwrap();
8692
    let heads = repo.bookmark_heads().unwrap();
8693
    let mut st = repo.load_state_history(&heads).unwrap();
8694
    let view = st.tree().view();
8695
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
8696
        .iter()
8697
        .map(|p| view.entries[*p].node)
8698
        .collect();
8699
    repo.load_graphs_of(&mut st, &nodes).unwrap();
8700
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
8701
    assert_eq!(st.built_count(), 2);
8702
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
8703
    assert_eq!((shed, st.built_count()), (2, 0));
8704
    // A later change applies on top of the shed history.
8705
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
8706
    let h3 = repo.commit("third", &[]).unwrap();
8707
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
8708
    st.add_known(h3, skeleton, texts);
8709
    repo.load_graphs_of(&mut st, &nodes).unwrap();
8710
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
8711
    assert_eq!(after[1], before[1]);
8712
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
8713
}
8714
8715
#[test]
8716
fn many_edited_files_diff_in_parallel() {
8717
    // Enough edited files that the builder diffs them in parallel; the
8718
    // commit must hold exactly what is on disk, and a second snapshot
8719
    // must find nothing left to commit.
8720
    hermetic();
8721
    let dir = tempfile::tempdir().unwrap();
8722
    let root = dir.path();
8723
    let repo = Repo::init(root).unwrap();
8724
    let text = |i: usize, round: usize| {
8725
        let mut s = String::new();
8726
        for line in 0..50 {
8727
            if round > 0 && line % 7 == i % 7 {
8728
                s.push_str(&format!("edited {round} {i} {line}\n"));
8729
            } else {
8730
                s.push_str(&format!("file {i} line {line}\n"));
8731
            }
8732
        }
8733
        if round > 0 && i.is_multiple_of(3) {
8734
            s.push_str("appended\n");
8735
        }
8736
        s
8737
    };
8738
    for i in 0..40 {
8739
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
8740
    }
8741
    repo.commit("first", &[]).unwrap();
8742
    for i in 0..40 {
8743
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
8744
    }
8745
    let h = repo.commit("edit every file", &[]).unwrap();
8746
    let snap = repo.load_state(&[h]).unwrap().materialize();
8747
    for i in 0..40 {
8748
        let want = text(i, 1);
8749
        assert!(
8750
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
8751
            "d/f{i}.txt as committed"
8752
        );
8753
    }
8754
    assert!(
8755
        repo.commit("nothing", &[]).is_err(),
8756
        "nothing left to commit"
8757
    );
8758
}
8759
8760
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
8761
/// is known (fetch printed "up to date" while main was behind), a change
8762
/// only fetched resolves and says where it is, and a checkout whose only
8763
/// remote is not `origin` uses that one.
8764
#[test]
8765
fn a_fetched_change_shows_as_behind_and_resolves() {
8766
    hermetic();
8767
    let dir = tempfile::tempdir().unwrap();
8768
    let root = dir.path();
8769
    let origin = Repo::init(&root.join("origin")).unwrap();
8770
    drop(origin);
8771
    let url = root.join("origin").to_string_lossy().to_string();
8772
    let a = Repo::clone(&url, &root.join("a"))
8773
        .unwrap()
8774
        .with_home(root.join("home-a"));
8775
    write(&root.join("a"), "f.txt", b"one\n");
8776
    a.commit("one", &[]).unwrap();
8777
    a.push("origin", false).unwrap();
8778
    let b = Repo::clone(&url, &root.join("b"))
8779
        .unwrap()
8780
        .with_home(root.join("home-b"));
8781
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
8782
8783
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
8784
    let h2 = a.commit("two", &[]).unwrap();
8785
    a.push("origin", false).unwrap();
8786
    b.fetch("origin").unwrap();
8787
    // Fetched, not pulled: one behind, the change found and placed.
8788
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
8789
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
8790
    assert_eq!(
8791
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
8792
            .unwrap(),
8793
        h2
8794
    );
8795
    assert_eq!(
8796
        b.remote_only_location(&h2).unwrap().as_deref(),
8797
        Some("origin/main")
8798
    );
8799
    // Fetching again changes nothing: still behind, which is what the
8800
    // CLI now says rather than "up to date".
8801
    b.fetch("origin").unwrap();
8802
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
8803
    b.pull("origin").unwrap();
8804
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
8805
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
8806
8807
    // One remote, not called origin: it is the default.
8808
    let mut c = Repo::init(&root.join("c")).unwrap();
8809
    assert_eq!(c.default_remote(), "origin");
8810
    c.config.set("remote.earth.url", &url).unwrap();
8811
    assert_eq!(c.default_remote(), "earth");
8812
    c.config.set("remote.origin.url", &url).unwrap();
8813
    assert_eq!(c.default_remote(), "origin");
8814
}
8815
8816
/// oxygen#57: a clone from a relative local path records the remote as an
8817
/// absolute path, so fetch still finds it from inside the clone.
8818
#[test]
8819
fn a_clone_from_a_relative_path_records_it_absolute() {
8820
    hermetic();
8821
    let dir = tempfile::tempdir().unwrap();
8822
    let root = dir.path();
8823
    Repo::init(&root.join("origin")).unwrap();
8824
    let rel = crate::protocol::stored_url("relative/repo");
8825
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
8826
    assert_eq!(
8827
        crate::protocol::stored_url("https://hub.example/o/n"),
8828
        "https://hub.example/o/n"
8829
    );
8830
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
8831
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
8832
    // A bucket is kept as written: it is not a path.
8833
    assert_eq!(
8834
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
8835
        "s3://bucket/prefix?profile=p"
8836
    );
8837
    let url = root.join("origin").to_string_lossy().to_string();
8838
    let b = Repo::clone(&url, &root.join("b")).unwrap();
8839
    assert_eq!(b.config.remotes["origin"], url);
8840
    b.fetch("origin").unwrap();
8841
}
8842
8843
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
8844
/// and gets its subrepos at their pins from this workspace's copies, with
8845
/// their remotes pointing where the subrepos come from.
8846
#[test]
8847
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
8848
    hermetic();
8849
    let dir = tempfile::tempdir().unwrap();
8850
    let root = dir.path();
8851
    Repo::init(&root.join("lib-origin")).unwrap();
8852
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8853
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8854
        .unwrap()
8855
        .with_home(root.join("home"));
8856
    write(&root.join("lib"), "lib.txt", b"v1\n");
8857
    let l1 = lib.commit("lib v1", &[]).unwrap();
8858
    assert!(lib.push("origin", false).unwrap()[0].ok);
8859
8860
    let app_dir = root.join("app");
8861
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8862
    write(&app_dir, "main.txt", b"app\n");
8863
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8864
    app.commit("app with lib", &[]).unwrap();
8865
    // A second bookmark, and the main workspace on another.
8866
    app.bookmark_create("develop", None).unwrap();
8867
    app.bookmark_create("feature", None).unwrap();
8868
    let mut app = app;
8869
    app.bookmark_switch("feature", false).unwrap();
8870
    assert_eq!(app.config.bookmark, "feature");
8871
8872
    // The library's origin goes away: the subrepo must come from here.
8873
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
8874
    let heads = app.resolve_heads("develop").unwrap();
8875
    let ws = app
8876
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
8877
        .unwrap();
8878
    assert_eq!(
8879
        ws.config.bookmark, "develop",
8880
        "the new workspace is on develop"
8881
    );
8882
    assert_eq!(
8883
        app.config.bookmark, "feature",
8884
        "and this one stays on its own"
8885
    );
8886
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
8887
    assert_eq!(
8888
        sub.config.remotes["origin"], lib_url,
8889
        "its origin is the subrepo's URL"
8890
    );
8891
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
8892
    assert_eq!(
8893
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
8894
        b"v1\n"
8895
    );
8896
}
8897
8898
/// Revsets (docs/revset_query_language.md): symbols, relations, set
8899
/// operators and the predicates, over a small graph with two heads and
8900
/// a rename.
8901
#[test]
8902
fn revsets_select_changes_by_relation_author_text_date_and_path() {
8903
    hermetic();
8904
    let dir = tempfile::tempdir().unwrap();
8905
    let root = dir.path();
8906
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
8907
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
8908
        .unwrap();
8909
    write(root, "src/a.rs", b"one\n");
8910
    let a = repo.commit("first: add a", &[]).unwrap();
8911
    write(root, "src/a.rs", b"one\ntwo\n");
8912
    let b = repo.commit("second: grow a", &[]).unwrap();
8913
    // A second head, independent of b: a new file on top of a.
8914
    repo.checkout(&[a], false, "checkout a").unwrap();
8915
    write(root, "docs/notes.md", b"notes\n");
8916
    let c = repo.commit("third: notes", &[]).unwrap();
8917
    // Back to both heads, then rename a.rs: the node keeps its identity.
8918
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
8919
        .unwrap();
8920
    fs::remove_file(root.join("src/a.rs")).unwrap();
8921
    write(root, "src/z.rs", b"one\ntwo\n");
8922
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
8923
    let wc = repo.working_copy().unwrap().0;
8924
    // A saved revset is checked when set.
8925
    repo.set_user_config("revset.mine", "author(me) & ::main")
8926
        .unwrap();
8927
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
8928
    let set = |src: &str| -> Vec<ChangeHash> {
8929
        let mut v = repo.revset(src).unwrap().hashes;
8930
        v.sort();
8931
        v
8932
    };
8933
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
8934
        let mut v = hs.to_vec();
8935
        v.sort();
8936
        v
8937
    };
8938
8939
    // Changes commute: a new file depends on nothing and the rename on the
8940
    // file's creation, so the graph is a, b->a, d->a, c, and the working
8941
    // copy on the three heads b, c, d.
8942
    let heads = sorted(&repo.bookmark_heads().unwrap());
8943
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
8944
    assert!(heads.contains(&d) && heads.contains(&c));
8945
    // Symbols and closures.
8946
    assert_eq!(set("main"), heads);
8947
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
8948
    assert_eq!(set("@"), vec![wc]);
8949
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
8950
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
8951
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
8952
    assert_eq!(
8953
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
8954
        sorted(&[a, b])
8955
    );
8956
    // Ranges: what main has beyond b, and `..` forms.
8957
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
8958
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
8959
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
8960
    // Operators and precedence: ~ binds tighter than &, & than |.
8961
    assert_eq!(
8962
        set(&format!("::main ~ #{}", d.short(12))),
8963
        sorted(&[a, b, c])
8964
    );
8965
    assert_eq!(
8966
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
8967
        sorted(&[b, c])
8968
    );
8969
    assert_eq!(set("all() ~ ::main"), vec![wc]);
8970
    // Relations.
8971
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
8972
    head_deps.sort();
8973
    head_deps.dedup();
8974
    assert_eq!(set("deps(main)"), head_deps);
8975
    let on_a: Vec<ChangeHash> = [b, c, d]
8976
        .into_iter()
8977
        .filter(|h| meta(h).deps.contains(&a))
8978
        .collect();
8979
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
8980
    assert_eq!(set("heads(::main)"), heads);
8981
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
8982
    assert_eq!(
8983
        set(&format!(
8984
            "heads(#{} | #{} | #{})",
8985
            a.short(12),
8986
            b.short(12),
8987
            c.short(12)
8988
        )),
8989
        sorted(&[b, c])
8990
    );
8991
    assert_eq!(set("latest(::main, 1)"), vec![d]);
8992
    assert_eq!(set("kind(working-copy)"), vec![wc]);
8993
    assert_eq!(set("none()"), vec![]);
8994
    // Predicates: author by name, email, key prefix and `me`.
8995
    let key = repo.config.author_key.unwrap();
8996
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
8997
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
8998
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
8999
    assert_eq!(set("author(me) & ::main").len(), 4);
9000
    assert_eq!(set("author(nobody)"), vec![]);
9001
    assert_eq!(set("description(notes)"), vec![c]);
9002
    assert_eq!(set("description(\"rename a\")"), vec![d]);
9003
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
9004
    assert_eq!(set("date(..2000-01-01)"), vec![]);
9005
    // touches follows the node through the rename, in the current state.
9006
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
9007
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
9008
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
9009
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
9010
    // Newest first in the result order.
9011
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
9012
    // The saved revset, and errors that say what is wrong.
9013
    assert_eq!(set("mine()").len(), 4);
9014
    let e = repo.revset("nosuch()").unwrap_err().to_string();
9015
    assert!(e.contains("unknown function nosuch()"), "{e}");
9016
    let e = repo.revset("main &").unwrap_err().to_string();
9017
    assert!(e.contains("at character"), "{e}");
9018
    let e = repo.revset("zzzz").unwrap_err().to_string();
9019
    assert!(e.contains("no change matches"), "{e}");
9020
    let e = repo
9021
        .revset_with_budget("::main", std::time::Duration::ZERO)
9022
        .unwrap_err()
9023
        .to_string();
9024
    assert!(e.contains("budget"), "{e}");
9025
    // The log entries carry the bookmark's heads and the working copy.
9026
    let entries = repo.log_revset("::@").unwrap();
9027
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
9028
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
9029
    // push); then a signed change, a tag, and a revocation.
9030
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
9031
    assert_eq!(set("signed_by(me)"), vec![]);
9032
    repo.sign_change(&d).unwrap();
9033
    assert_eq!(set("signed_by(me)"), vec![d]);
9034
    assert_eq!(set("signed_by([email protected])"), vec![d]);
9035
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
9036
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
9037
    assert_eq!(set("delegated()"), vec![]);
9038
    assert_eq!(set("revoked()"), vec![]);
9039
    assert_eq!(set("attested(tag)"), vec![]);
9040
    repo.tag_create("v1", &[b], "first").unwrap();
9041
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
9042
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
9043
    assert_eq!(set("attested(receipt)"), vec![]);
9044
    assert_eq!(set("built(test)"), vec![]);
9045
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
9046
    assert!(e.contains("tag, receipt or ref"), "{e}");
9047
    repo.revoke_identity(&key, "test").unwrap();
9048
    assert_eq!(set("revoked()"), vec![d]);
9049
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
9050
    // independent(X, IN): what could ship without X. c and d neither
9051
    // depend on b nor are depended on by it; a is below, the working copy
9052
    // above.
9053
    assert_eq!(
9054
        set(&format!("independent(#{}, ::@)", b.short(12))),
9055
        sorted(&[c, d])
9056
    );
9057
    assert_eq!(
9058
        set(&format!("independent(#{}, ::main)", a.short(12))),
9059
        vec![c]
9060
    );
9061
    // conflicts(S): nothing conflicts yet; then two edits of one line.
9062
    assert_eq!(set("conflicts()"), vec![]);
9063
    assert_eq!(set("conflicts(main)"), vec![]);
9064
    // (The saved revset above edited the user config under the root:
9065
    // discard it.)
9066
    repo.checkout(&[a], true, "checkout a").unwrap();
9067
    write(root, "src/a.rs", b"one\nTWO\n");
9068
    let e = repo
9069
        .commit("fifth: the other edit of line two", &[])
9070
        .unwrap();
9071
    repo.checkout(&repo.bookmark_heads().unwrap(), true, "checkout main")
9072
        .unwrap();
9073
    let conflicted = repo.revset("conflicts()").unwrap().hashes;
9074
    assert!(
9075
        conflicted.contains(&e) && conflicted.contains(&b),
9076
        "{conflicted:?} should hold b and e"
9077
    );
9078
    assert!(!conflicted.contains(&c));
9079
    assert_eq!(set("conflicts() & author(nobody)"), vec![]);
9080
}
9081
9082
#[test]
9083
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
9084
    let dir = tempfile::tempdir().unwrap();
9085
    let root = dir.path();
9086
    let home = root.join("home");
9087
    // Ada's identity lives in the user file; repository `a` pins the same
9088
    // key in its own file, repository `b` names none.
9089
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
9090
    let (key, _) = a
9091
        .create_identity("Ada", "[email protected]", IdentityScope::User)
9092
        .unwrap();
9093
    a.config.set("author.key", &key.to_hex()).unwrap();
9094
    a.save_config().unwrap();
9095
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
9096
    let r = a
9097
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
9098
        .unwrap();
9099
    assert_eq!(
9100
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
9101
        r.new.to_hex(),
9102
        "the user file follows"
9103
    );
9104
    assert_eq!(
9105
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
9106
        r.new.to_hex(),
9107
        "the pinning repository follows"
9108
    );
9109
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
9110
    assert_eq!(
9111
        b.config.author_key,
9112
        Some(r.new),
9113
        "a checkout without a pin follows the user file"
9114
    );
9115
    // A repository-scoped identity leaves the user file alone.
9116
    let other_home = root.join("home2");
9117
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
9118
    let (ck, _) = c
9119
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
9120
        .unwrap();
9121
    assert!(!other_home.join("config.toml").exists());
9122
    let r2 = c.rotate_identity().unwrap();
9123
    assert_ne!(r2.new, ck);
9124
    assert_eq!(
9125
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
9126
        r2.new.to_hex()
9127
    );
9128
    assert!(
9129
        !other_home.join("config.toml").exists(),
9130
        "a repository-scoped identity stays repository-scoped"
9131
    );
9132
    // Several delegates in one rotation; a repeat is refused.
9133
    let (d1, d2) = (
9134
        SecretKey::generate().identity("D1", "d1@x", 1),
9135
        SecretKey::generate().identity("D2", "d2@x", 1),
9136
    );
9137
    let r3 = c
9138
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
9139
        .unwrap();
9140
    assert_eq!(r3.identity.delegates.len(), 2);
9141
    assert!(c
9142
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
9143
        .is_err());
9144
}
9145
9146
/// Two unrelated histories that both add the same file, joined by two
9147
/// independent merges on two branches, then those branches merged: Git
9148
/// merges identical additions cleanly, and the import must too (#71,
9149
/// found in VS Code's history).
9150
#[test]
9151
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
9152
    // Batches of one: every merge renders apart from the state, where a
9153
    // file whose graph the state had built came out empty (#71).
9154
    crate::repo::git::set_merge_batch_for_tests(Some(1));
9155
    hermetic();
9156
    if std::process::Command::new("git")
9157
        .arg("--version")
9158
        .output()
9159
        .is_err()
9160
    {
9161
        eprintln!("git not installed; skipping");
9162
        return;
9163
    }
9164
    let dir = tempfile::tempdir().unwrap();
9165
    let root = dir.path();
9166
    let g = root.join("src.git");
9167
    fs::create_dir_all(&g).unwrap();
9168
    let git = |args: &[&str]| -> String {
9169
        let out = std::process::Command::new("git")
9170
            .arg("-C")
9171
            .arg(&g)
9172
            .args([
9173
                "-c",
9174
                "user.name=Grace",
9175
                "-c",
9176
                "[email protected]",
9177
                "-c",
9178
                "commit.gpgsign=false",
9179
            ])
9180
            .args(args)
9181
            .output()
9182
            .unwrap();
9183
        assert!(
9184
            out.status.success(),
9185
            "git {args:?}: {}",
9186
            String::from_utf8_lossy(&out.stderr)
9187
        );
9188
        String::from_utf8_lossy(&out.stdout).trim().to_string()
9189
    };
9190
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
9191
    // History A: main.
9192
    git(&["init", "-q", "-b", "main"]);
9193
    write(&g, "gulpfile.js", text);
9194
    write(&g, "a.txt", b"a\n");
9195
    git(&["add", "."]);
9196
    git(&["commit", "-q", "-m", "A root"]);
9197
    // History B: an unrelated root adding the same file, identical.
9198
    git(&["checkout", "-q", "--orphan", "fork"]);
9199
    git(&["rm", "-q", "-r", "--cached", "."]);
9200
    for f in ["gulpfile.js", "a.txt"] {
9201
        let _ = fs::remove_file(g.join(f));
9202
    }
9203
    write(&g, "gulpfile.js", text);
9204
    write(&g, "b.txt", b"b\n");
9205
    git(&["add", "."]);
9206
    git(&["commit", "-q", "-m", "B root"]);
9207
    // Two branches from main, each joining B on its own.
9208
    git(&["checkout", "-q", "-b", "one", "main"]);
9209
    git(&[
9210
        "merge",
9211
        "-q",
9212
        "--no-ff",
9213
        "--allow-unrelated-histories",
9214
        "-m",
9215
        "join on one",
9216
        "fork",
9217
    ]);
9218
    git(&["checkout", "-q", "-b", "two", "main"]);
9219
    write(&g, "a.txt", b"a\ntwo\n");
9220
    git(&["commit", "-q", "-am", "work on two"]);
9221
    git(&[
9222
        "merge",
9223
        "-q",
9224
        "--no-ff",
9225
        "--allow-unrelated-histories",
9226
        "-m",
9227
        "join on two",
9228
        "fork",
9229
    ]);
9230
    // Then the two joins meet, and the file is reformatted after.
9231
    git(&["checkout", "-q", "main"]);
9232
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
9233
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
9234
    write(
9235
        &g,
9236
        "gulpfile.js",
9237
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
9238
    );
9239
    git(&["commit", "-q", "-am", "after"]);
9240
9241
    let dest = root.join("dest");
9242
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
9243
    repo.import_git(&g, "main").unwrap();
9244
    let v = repo.verify_git_import(&g, "main").unwrap();
9245
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9246
    assert_eq!(
9247
        fs::read(dest.join("gulpfile.js")).unwrap(),
9248
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
9249
    );
9250
}
9251
9252
/// As above, but the two joins keep different copies (each branch had a
9253
/// different version when it joined), and later work edits each copy:
9254
/// the shape of VS Code's c67ef57cda90 (#71).
9255
#[test]
9256
fn git_import_joins_where_each_join_kept_a_different_copy() {
9257
    // Batches of one: every merge renders apart from the state, where a
9258
    // file whose graph the state had built came out empty (#71).
9259
    crate::repo::git::set_merge_batch_for_tests(Some(1));
9260
    hermetic();
9261
    if std::process::Command::new("git")
9262
        .arg("--version")
9263
        .output()
9264
        .is_err()
9265
    {
9266
        eprintln!("git not installed; skipping");
9267
        return;
9268
    }
9269
    let dir = tempfile::tempdir().unwrap();
9270
    let root = dir.path();
9271
    let g = root.join("src.git");
9272
    fs::create_dir_all(&g).unwrap();
9273
    let run = |args: &[&str]| {
9274
        std::process::Command::new("git")
9275
            .arg("-C")
9276
            .arg(&g)
9277
            .args([
9278
                "-c",
9279
                "user.name=Grace",
9280
                "-c",
9281
                "[email protected]",
9282
                "-c",
9283
                "commit.gpgsign=false",
9284
            ])
9285
            .args(args)
9286
            .output()
9287
            .unwrap()
9288
    };
9289
    let git = |args: &[&str]| -> String {
9290
        let out = run(args);
9291
        assert!(
9292
            out.status.success(),
9293
            "git {args:?}: {}",
9294
            String::from_utf8_lossy(&out.stderr)
9295
        );
9296
        String::from_utf8_lossy(&out.stdout).trim().to_string()
9297
    };
9298
    git(&["init", "-q", "-b", "main"]);
9299
    write(
9300
        &g,
9301
        "gulpfile.js",
9302
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
9303
    );
9304
    git(&["add", "."]);
9305
    git(&["commit", "-q", "-m", "A root"]);
9306
    write(
9307
        &g,
9308
        "gulpfile.js",
9309
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
9310
    );
9311
    git(&["commit", "-q", "-am", "whitespace"]);
9312
    git(&["checkout", "-q", "--orphan", "fork"]);
9313
    git(&["rm", "-q", "-r", "--cached", "."]);
9314
    let _ = fs::remove_file(g.join("gulpfile.js"));
9315
    write(
9316
        &g,
9317
        "gulpfile.js",
9318
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
9319
    );
9320
    git(&["add", "."]);
9321
    git(&["commit", "-q", "-m", "B root"]);
9322
    // Branch one joins B keeping main's copy; branch two keeps B's.
9323
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
9324
        git(&["checkout", "-q", "-b", branch, "main"]);
9325
        let _ = run(&[
9326
            "merge",
9327
            "-q",
9328
            "--no-ff",
9329
            "--allow-unrelated-histories",
9330
            "-m",
9331
            "join",
9332
            "fork",
9333
        ]);
9334
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
9335
        git(&["add", "gulpfile.js"]);
9336
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
9337
    }
9338
    // Each branch then edits its copy.
9339
    git(&["checkout", "-q", "one"]);
9340
    write(
9341
        &g,
9342
        "gulpfile.js",
9343
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
9344
    );
9345
    git(&["commit", "-q", "-am", "tslint on one"]);
9346
    git(&["checkout", "-q", "two"]);
9347
    write(
9348
        &g,
9349
        "gulpfile.js",
9350
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
9351
    );
9352
    write(&g, "extra.txt", b"x\n");
9353
    write(&g, "more.txt", b"m\n");
9354
    git(&["add", "."]);
9355
    git(&["commit", "-q", "-am", "fmt on two"]);
9356
    // They meet: resolved by hand.
9357
    git(&["checkout", "-q", "one"]);
9358
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
9359
    write(
9360
        &g,
9361
        "gulpfile.js",
9362
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
9363
    );
9364
    git(&["add", "gulpfile.js"]);
9365
    git(&["commit", "-q", "-m", "merge two into one"]);
9366
9367
    let dest = root.join("dest");
9368
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
9369
    repo.import_git(&g, "one").unwrap();
9370
    let v = repo.verify_git_import(&g, "one").unwrap();
9371
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9372
}
9373
9374
/// oxygen#68: on a store that is not this disk's directory, the operation
9375
/// head is the store's reference record, moved by compare-and-swap. Two
9376
/// handles recording from the same head both get through, merged; a swap
9377
/// from a stale version is refused; a second repository cannot start on a
9378
/// store that already holds one.
9379
#[test]
9380
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
9381
    use crate::strata::{MemoryStore, Store as _};
9382
    let backend = std::sync::Arc::new(MemoryStore::new());
9383
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
9384
    let dir = tempfile::tempdir().unwrap();
9385
    let a = Repo::init(dir.path()).unwrap();
9386
    assert!(
9387
        !dir.path().join(".oxy/ops/head").exists(),
9388
        "the head is not a file"
9389
    );
9390
    let (h0, op0) = a.head_op().unwrap();
9391
    let record = backend
9392
        .read_ref(HEAD_RECORD)
9393
        .unwrap()
9394
        .expect("the head is the store's record");
9395
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
9396
9397
    let b = Repo::open(dir.path()).unwrap();
9398
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
9399
    let mut va = op0.view.clone();
9400
    va.bookmarks.insert("from-a".into(), state);
9401
    let mut vb = op0.view.clone();
9402
    vb.bookmarks.insert("from-b".into(), state);
9403
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
9404
    assert_eq!(b.head_ref().unwrap(), rb);
9405
    // a recorded from h0 too: the head moved, so the two are merged.
9406
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
9407
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
9408
    assert_eq!(head, ra);
9409
    assert!(
9410
        op.command.ends_with("(merged with a concurrent operation)"),
9411
        "{}",
9412
        op.command
9413
    );
9414
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
9415
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
9416
9417
    // A swap from a version that is no longer current moves nothing.
9418
    let (h, v) = a.read_head().unwrap();
9419
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
9420
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
9421
    a.refresh().unwrap();
9422
    assert_eq!(a.head_ref().unwrap(), rb);
9423
9424
    let other = tempfile::tempdir().unwrap();
9425
    let err = Repo::init(other.path())
9426
        .err()
9427
        .expect("the store already holds a log")
9428
        .to_string();
9429
    assert!(
9430
        err.contains("already holds a repository's operation log"),
9431
        "{err}"
9432
    );
9433
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
9434
}
9435
9436
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
9437
/// objects and operation head there, with `.oxy/cache` in front: it works
9438
/// as one on disk does, reopens, and survives losing its cache.
9439
#[test]
9440
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
9441
    hermetic();
9442
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
9443
        return;
9444
    }
9445
    let dir = tempfile::tempdir().unwrap();
9446
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
9447
    let url = format!("dir://{}", bucket.display());
9448
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
9449
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
9450
    write(&root, "a.txt", b"one\n");
9451
    let h1 = repo.commit("First", &[]).unwrap();
9452
    write(&root, "a.txt", b"one\ntwo\n");
9453
    let h2 = repo.commit("Second", &[]).unwrap();
9454
    assert!(
9455
        !root.join(".oxy/ops/head").exists(),
9456
        "the head is in the store"
9457
    );
9458
    assert!(bucket.join("ops/head").is_file());
9459
    assert!(root.join(".oxy/cache").is_dir());
9460
    drop(repo);
9461
9462
    // Reopened, and again with no cache at all: everything comes from the store.
9463
    for drop_cache in [false, true] {
9464
        if drop_cache {
9465
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
9466
        }
9467
        let repo = Repo::open(&root).unwrap();
9468
        let log: Vec<String> = repo
9469
            .op_log()
9470
            .unwrap()
9471
            .into_iter()
9472
            .map(|(_, op)| op.command)
9473
            .collect();
9474
        assert!(log.len() >= 3, "{log:?}");
9475
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
9476
        let heads = repo
9477
            .store()
9478
            .get_state(&repo.view().unwrap().bookmarks["main"])
9479
            .unwrap()
9480
            .heads;
9481
        assert_eq!(heads, vec![h2]);
9482
        assert_eq!(
9483
            repo.load_state(&heads).unwrap().materialize().files.len(),
9484
            1
9485
        );
9486
    }
9487
9488
    // A second repository cannot start on the same store.
9489
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
9490
        .err()
9491
        .unwrap()
9492
        .to_string();
9493
    assert!(
9494
        err.contains("already holds a repository's operation log"),
9495
        "{err}"
9496
    );
9497
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
9498
        .err()
9499
        .unwrap()
9500
        .to_string();
9501
    assert!(err.contains("cannot open that kind of store"), "{err}");
9502
}
9503
9504
/// oxygen#75: the prompt's quick check agrees with status in a repository
9505
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
9506
/// another state, clean again once that pin is committed. (It compared the
9507
/// subrepo's directory as if it were a file, so it was always dirty.)
9508
#[test]
9509
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
9510
    hermetic();
9511
    let dir = tempfile::tempdir().unwrap();
9512
    let root = dir.path();
9513
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9514
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9515
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9516
        .unwrap()
9517
        .with_home(root.join("home"));
9518
    write(&root.join("lib"), "lib.txt", b"v1\n");
9519
    lib.commit("lib v1", &[]).unwrap();
9520
    assert!(lib.push("origin", false).unwrap()[0].ok);
9521
    let app_dir = root.join("app");
9522
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
9523
    write(&app_dir, "main.txt", b"app\n");
9524
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9525
    app.commit("app with lib", &[]).unwrap();
9526
    // Out of the racy window, so the stat-only path decides.
9527
    std::thread::sleep(std::time::Duration::from_millis(2100));
9528
    let reopen = || Repo::open(&app_dir).unwrap();
9529
    assert_eq!(
9530
        reopen().quick_dirty().unwrap(),
9531
        Some(false),
9532
        "clean, as status says"
9533
    );
9534
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
9535
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
9536
    nested.commit("lib v2", &[]).unwrap();
9537
    assert_eq!(
9538
        reopen().quick_dirty().unwrap(),
9539
        Some(true),
9540
        "the subrepo moved"
9541
    );
9542
    reopen().commit("pin lib v2", &[]).unwrap();
9543
    std::thread::sleep(std::time::Duration::from_millis(2100));
9544
    assert_eq!(
9545
        reopen().quick_dirty().unwrap(),
9546
        Some(false),
9547
        "the new pin is committed"
9548
    );
9549
}
9550
9551
#[test]
9552
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
9553
    // oxygen#72: a .oxymodules section with no subrepo behind it.
9554
    hermetic();
9555
    let dir = tempfile::tempdir().unwrap();
9556
    let root = dir.path();
9557
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9558
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9559
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9560
        .unwrap()
9561
        .with_home(root.join("home"));
9562
    write(&root.join("lib"), "lib.txt", b"v1\n");
9563
    lib.commit("lib v1", &[]).unwrap();
9564
    assert!(lib.push("origin", false).unwrap()[0].ok);
9565
    let app_dir = root.join("app");
9566
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
9567
    write(
9568
        &app_dir,
9569
        ".oxymodules",
9570
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
9571
    );
9572
    let unpinned = app.unpinned_modules().unwrap();
9573
    assert_eq!(unpinned.len(), 1);
9574
    assert_eq!(unpinned[0].0, "libs/lib");
9575
    assert_eq!(unpinned[0].1.url, lib_url);
9576
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
9577
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9578
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
9579
}
9580
9581
#[test]
9582
fn the_bookmark_revset_function_names_only_bookmarks() {
9583
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
9584
    hermetic();
9585
    let dir = tempfile::tempdir().unwrap();
9586
    let repo = Repo::init(dir.path()).unwrap();
9587
    write(dir.path(), "a.txt", b"a\n");
9588
    let a = repo.commit("A", &[]).unwrap();
9589
    write(dir.path(), "b.txt", b"b\n");
9590
    let b = repo.commit("B", &[]).unwrap();
9591
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
9592
    heads.sort();
9593
    let mut want = repo.bookmark_heads().unwrap();
9594
    want.sort();
9595
    assert_eq!(heads, want);
9596
    assert!(heads.contains(&b));
9597
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
9598
    // A change prefix is a symbol, not a bookmark.
9599
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
9600
    assert!(repo.revset(&prefix).is_ok());
9601
    let e = repo
9602
        .revset(&format!("bookmark({prefix})"))
9603
        .unwrap_err()
9604
        .to_string();
9605
    assert!(e.contains("no such bookmark"), "{e}");
9606
}
9607
9608
#[test]
9609
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
9610
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
9611
    // pinning the subrepo, and the nested repository on disk at that pin.
9612
    hermetic();
9613
    let dir = tempfile::tempdir().unwrap();
9614
    let root = dir.path();
9615
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9616
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9617
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9618
        .unwrap()
9619
        .with_home(root.join("home"));
9620
    write(&root.join("lib"), "lib.txt", b"v1\n");
9621
    lib.commit("lib v1", &[]).unwrap();
9622
    assert!(lib.push("origin", false).unwrap()[0].ok);
9623
    let app_dir = root.join("app");
9624
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
9625
    write(&app_dir, "main.txt", b"app\n");
9626
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9627
    // The stale state: registered in .oxymodules, never pinned.
9628
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
9629
    app.commit("initial", &[]).unwrap();
9630
    let stale = app.bookmark_heads().unwrap();
9631
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
9632
    app.commit("pin lib", &[]).unwrap();
9633
    let newer = app.bookmark_heads().unwrap();
9634
    app.checkout(&stale, false, "test").unwrap();
9635
    write(&app_dir, "notes.txt", b"mine\n");
9636
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
9637
    assert_eq!(carried, vec!["notes.txt".to_string()]);
9638
    assert!(app_dir.join("notes.txt").exists());
9639
}
9640
9641
#[test]
9642
fn a_bookmark_only_behind_its_remote_catches_up() {
9643
    // oxygen#74: switch takes the remote's state rather than a stale one.
9644
    hermetic();
9645
    let dir = tempfile::tempdir().unwrap();
9646
    let root = dir.path();
9647
    let _origin = Repo::init(&root.join("origin")).unwrap();
9648
    let url = root.join("origin").to_string_lossy().to_string();
9649
    let one = Repo::clone(&url, &root.join("one"))
9650
        .unwrap()
9651
        .with_home(root.join("home"));
9652
    write(&root.join("one"), "a.txt", b"a\n");
9653
    one.commit("A", &[]).unwrap();
9654
    assert!(one.push("origin", false).unwrap()[0].ok);
9655
    let two = Repo::clone(&url, &root.join("two"))
9656
        .unwrap()
9657
        .with_home(root.join("home"));
9658
    write(&root.join("two"), "b.txt", b"b\n");
9659
    two.commit("B", &[]).unwrap();
9660
    assert!(two.push("origin", false).unwrap()[0].ok);
9661
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
9662
    one.fetch("origin").unwrap();
9663
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
9664
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
9665
    // Local work the remote lacks: left alone.
9666
    write(&root.join("one"), "c.txt", b"c\n");
9667
    one.commit("C", &[]).unwrap();
9668
    write(&root.join("two"), "d.txt", b"d\n");
9669
    two.commit("D", &[]).unwrap();
9670
    assert!(two.push("origin", false).unwrap()[0].ok);
9671
    one.fetch("origin").unwrap();
9672
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
9673
}
9674
9675
#[test]
9676
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
9677
    // oxygen#83: remotes earth and gcs, origin removed.
9678
    hermetic();
9679
    let dir = tempfile::tempdir().unwrap();
9680
    let root = dir.path();
9681
    let _up = Repo::init(&root.join("up")).unwrap();
9682
    let url = root.join("up").to_string_lossy().to_string();
9683
    let other = Repo::clone(&url, &root.join("other"))
9684
        .unwrap()
9685
        .with_home(root.join("home"));
9686
    write(&root.join("other"), "a.txt", b"a\n");
9687
    other.commit("a", &[]).unwrap();
9688
    assert!(other.push("origin", false).unwrap()[0].ok);
9689
    let mut one = Repo::clone(&url, &root.join("one"))
9690
        .unwrap()
9691
        .with_home(root.join("home"));
9692
    one.config.set("remote.earth.url", &url).unwrap();
9693
    one.config.set("remote.gcs.url", &url).unwrap();
9694
    one.config.set("remote.origin.url", "").unwrap();
9695
    one.save_config().unwrap();
9696
    write(&root.join("other"), "b.txt", b"b\n");
9697
    other.commit("b", &[]).unwrap();
9698
    assert!(other.push("origin", false).unwrap()[0].ok);
9699
    one.fetch("earth").unwrap();
9700
    let b = one
9701
        .bookmarks()
9702
        .unwrap()
9703
        .into_iter()
9704
        .find(|b| b.name == "main")
9705
        .unwrap();
9706
    assert_eq!(
9707
        (b.remote.as_deref(), b.behind),
9708
        (Some("earth"), Some(1)),
9709
        "a stale origin copy is not used"
9710
    );
9711
    assert_eq!(
9712
        one.default_remote(),
9713
        "origin",
9714
        "no default chosen among several"
9715
    );
9716
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
9717
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
9718
    one.config.set("core.remote", "earth").unwrap();
9719
    assert_eq!(one.default_remote(), "earth");
9720
}
9721
9722
#[test]
9723
fn a_missing_author_identity_says_how_to_fix_it() {
9724
    // oxygen#82: an agent home's author.key naming an identity the
9725
    // repository does not hold.
9726
    hermetic();
9727
    let dir = tempfile::tempdir().unwrap();
9728
    let mut repo = Repo::init(dir.path()).unwrap();
9729
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
9730
    repo.config.set("author.key", &missing.to_hex()).unwrap();
9731
    let e = repo.identity(&missing).unwrap_err().to_string();
9732
    assert!(
9733
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
9734
        "{e}"
9735
    );
9736
    assert!(e.contains("this repository's config"), "{e}");
9737
}
9738
9739
#[test]
9740
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
9741
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
9742
    // the working copy, a pull with nothing new left it there, and status
9743
    // said "clean".
9744
    hermetic();
9745
    let dir = tempfile::tempdir().unwrap();
9746
    let root = dir.path();
9747
    let _up = Repo::init(&root.join("up")).unwrap();
9748
    let url = root.join("up").to_string_lossy().to_string();
9749
    let other = Repo::clone(&url, &root.join("other"))
9750
        .unwrap()
9751
        .with_home(root.join("home"));
9752
    write(&root.join("other"), "a.txt", b"a\n");
9753
    other.commit("a", &[]).unwrap();
9754
    assert!(other.push("origin", false).unwrap()[0].ok);
9755
    let one = Repo::clone(&url, &root.join("one"))
9756
        .unwrap()
9757
        .with_home(root.join("home"));
9758
    write(&root.join("other"), "b.txt", b"b\n");
9759
    other.commit("b", &[]).unwrap();
9760
    assert!(other.push("origin", false).unwrap()[0].ok);
9761
    one.fetch("origin").unwrap();
9762
    // The bookmark moves; the working copy does not.
9763
    let theirs = one.resolve_heads("origin/main").unwrap();
9764
    one.bookmark_set("main", &theirs).unwrap();
9765
    assert!(!root.join("one/b.txt").exists());
9766
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
9767
    let r = one.pull("origin").unwrap();
9768
    assert!(
9769
        !r.changed && r.checked_out,
9770
        "nothing new, but the working copy caught up"
9771
    );
9772
    assert!(root.join("one/b.txt").exists());
9773
    assert_eq!(one.working_copy_behind().unwrap(), None);
9774
}
9775
9776
#[test]
9777
fn touched_nodes_cache_answers_as_the_changes_do() {
9778
    hermetic();
9779
    let dir = tempfile::tempdir().unwrap();
9780
    let repo = Repo::init(dir.path()).unwrap();
9781
    write(dir.path(), "a.txt", b"one\n");
9782
    write(dir.path(), "b.txt", b"x\n");
9783
    repo.snapshot("t").unwrap();
9784
    let c1 = repo.commit("first", &[]).unwrap();
9785
    write(dir.path(), "b.txt", b"y\n");
9786
    repo.snapshot("t").unwrap();
9787
    repo.commit("b only", &[]).unwrap();
9788
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
9789
    write(dir.path(), "c.txt", b"one\ntwo\n");
9790
    repo.snapshot("t").unwrap();
9791
    let c3 = repo.commit("rename and edit", &[]).unwrap();
9792
    // Uncommitted work, so the working copy touches a file too.
9793
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
9794
    repo.snapshot("t").unwrap();
9795
9796
    let path = dir.path().join(".oxy/index/touched");
9797
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
9798
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
9799
    assert!(path.exists(), "the first query writes the cache");
9800
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
9801
    assert_eq!(cold, warm, "the cache answers as the changes do");
9802
    let (wc, _) = repo.working_copy().unwrap();
9803
    assert_eq!(
9804
        cold,
9805
        vec![wc, c3, c1],
9806
        "renames followed, the working copy included"
9807
    );
9808
9809
    // Working-copy changes are not kept: they are replaced by every snapshot.
9810
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
9811
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
9812
    assert!(cached.contains(&c1) && cached.contains(&c3));
9813
9814
    // A damaged cache is ignored, not trusted.
9815
    let mut bytes = fs::read(&path).unwrap();
9816
    let last = bytes.len() - 40;
9817
    bytes[last] ^= 1;
9818
    fs::write(&path, &bytes).unwrap();
9819
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
9820
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
9821
    assert_eq!(hashes(touches), vec![c3, c1]);
9822
}
9823
9824
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
9825
/// file back where it was leave two placements at one place, which the
9826
/// tree shows as one file. Removing it, and then its directory, retires
9827
/// both, so no copy is left under a directory that is gone.
9828
#[test]
9829
fn git_import_removes_every_copy_of_a_file_at_one_place() {
9830
    hermetic();
9831
    if std::process::Command::new("git")
9832
        .arg("--version")
9833
        .output()
9834
        .is_err()
9835
    {
9836
        eprintln!("git not installed; skipping");
9837
        return;
9838
    }
9839
    let dir = tempfile::tempdir().unwrap();
9840
    let root = dir.path();
9841
    let g = root.join("src.git");
9842
    fs::create_dir_all(&g).unwrap();
9843
    let git = |args: &[&str]| {
9844
        let out = std::process::Command::new("git")
9845
            .arg("-C")
9846
            .arg(&g)
9847
            .args([
9848
                "-c",
9849
                "user.name=Grace",
9850
                "-c",
9851
                "[email protected]",
9852
                "-c",
9853
                "commit.gpgsign=false",
9854
            ])
9855
            .args(args)
9856
            .output()
9857
            .unwrap();
9858
        assert!(
9859
            out.status.success(),
9860
            "git {args:?}: {}",
9861
            String::from_utf8_lossy(&out.stderr)
9862
        );
9863
    };
9864
    git(&["init", "-q", "-b", "main"]);
9865
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
9866
    write(&g, "keep.txt", b"k\n");
9867
    git(&["add", "."]);
9868
    git(&["commit", "-qm", "base"]);
9869
    fs::create_dir_all(g.join("d/sub")).unwrap();
9870
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
9871
    git(&["commit", "-qm", "into sub"]);
9872
    git(&["checkout", "-qb", "side"]);
9873
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
9874
    git(&["commit", "-qm", "back, on side"]);
9875
    git(&["checkout", "-q", "main"]);
9876
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
9877
    git(&["commit", "-qm", "back, on main"]);
9878
    git(&["merge", "-q", "--no-edit", "side"]);
9879
    git(&["rm", "-rq", "d"]);
9880
    git(&["commit", "-qm", "d goes"]);
9881
9882
    let repo = Repo::init(&root.join("o")).unwrap();
9883
    repo.import_git(&g, "main").unwrap();
9884
    let v = repo.verify_git_import(&g, "main").unwrap();
9885
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9886
    let st = repo
9887
        .load_state_history(&repo.bookmark_heads().unwrap())
9888
        .unwrap();
9889
    let view = st.tree().view();
9890
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
9891
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
9892
}
9893
9894
/// oxygen#94: a state index's file histories are read, and checked by
9895
/// their own hashes, only when a file is built. One found damaged is an
9896
/// error that says so, the index is removed, and the next read rebuilds it.
9897
#[test]
9898
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
9899
    hermetic();
9900
    let dir = tempfile::tempdir().unwrap();
9901
    let repo = Repo::init(dir.path()).unwrap();
9902
    for i in 0..6 {
9903
        write(
9904
            dir.path(),
9905
            &format!("f{i}.txt"),
9906
            format!("one {i}\n").as_bytes(),
9907
        );
9908
    }
9909
    repo.snapshot("t").unwrap();
9910
    repo.commit("first", &[]).unwrap();
9911
    for i in 0..6 {
9912
        write(
9913
            dir.path(),
9914
            &format!("f{i}.txt"),
9915
            format!("one {i}\ntwo\n").as_bytes(),
9916
        );
9917
    }
9918
    repo.snapshot("t").unwrap();
9919
    repo.commit("second", &[]).unwrap();
9920
    let want: Vec<Vec<u8>> = (0..6)
9921
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
9922
        .collect();
9923
    // The index of the working copy's base, holding every file's history
9924
    // (a few changes behind, an index is replayed onto, not rewritten).
9925
    let (_, wc) = repo.working_copy().unwrap();
9926
    let base = repo.load_state_history(&wc.deps).unwrap();
9927
    repo.write_state_index(&wc.deps, &base);
9928
    for (i, w) in want.iter().enumerate() {
9929
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
9930
    }
9931
    let index = repo.state_indexes();
9932
    assert!(!index.is_empty(), "a state index was written");
9933
    // The histories are last in the file: damage the last of them.
9934
    let mut bytes = fs::read(&index[0]).unwrap();
9935
    let last = bytes.len() - 1;
9936
    bytes[last] ^= 0x40;
9937
    fs::write(&index[0], &bytes).unwrap();
9938
9939
    let reads: Vec<_> = (0..6)
9940
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
9941
        .collect();
9942
    let damaged: Vec<String> = reads
9943
        .iter()
9944
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
9945
        .collect();
9946
    assert_eq!(damaged.len(), 1, "{damaged:?}");
9947
    assert!(
9948
        damaged[0].contains("state index was damaged")
9949
            && damaged[0].contains("run the command again"),
9950
        "{}",
9951
        damaged[0]
9952
    );
9953
    // Every file reads right again, from an index rebuilt from history.
9954
    for (i, w) in want.iter().enumerate() {
9955
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
9956
    }
9957
}
9958
9959
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
9960
/// objects alone and in dependency order, and the last moves the bookmark.
9961
/// The remote ends with every change and the same state, and says how each
9962
/// part went.
9963
#[test]
9964
fn a_long_push_goes_in_parts() {
9965
    hermetic();
9966
    let dir = tempfile::tempdir().unwrap();
9967
    let root = dir.path();
9968
    let origin = root.join("origin");
9969
    Repo::init_bare_unbound(&origin).unwrap();
9970
    let main = root.join("main");
9971
    let mut repo = Repo::init(&main).unwrap();
9972
    repo.config
9973
        .set("remote.origin.url", &origin.to_string_lossy())
9974
        .unwrap();
9975
    // One byte: every change is a part of its own.
9976
    repo.config.set("push.batch-bytes", "1").unwrap();
9977
    repo.save_config().unwrap();
9978
    for i in 0..6 {
9979
        write(
9980
            &main,
9981
            &format!("f{i}.txt"),
9982
            format!("file {i}\n").as_bytes(),
9983
        );
9984
        repo.commit(&format!("c{i}"), &[]).unwrap();
9985
    }
9986
    let mut parts = Vec::new();
9987
    let results = repo
9988
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
9989
        .unwrap();
9990
    assert!(
9991
        results.iter().any(|r| r.ok && r.name == "main"),
9992
        "{results:?}"
9993
    );
9994
    assert_eq!(parts.len(), 6, "{parts:?}");
9995
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
9996
9997
    let remote = Repo::open(&origin).unwrap();
9998
    let heads = repo.bookmark_heads().unwrap();
9999
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
10000
    assert_eq!(
10001
        remote.log_state(&heads).unwrap().len(),
10002
        repo.log_state(&heads).unwrap().len()
10003
    );
10004
    // A push of objects alone reports how it went, as `objects`.
10005
    let got = remote
10006
        .receive_push(Bundle::default(), vec![], None, vec![])
10007
        .unwrap();
10008
    assert_eq!(got.len(), 1);
10009
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
10010
}
10011
10012
/// oxygen#133: one change whose blobs pass `push.batch-bytes` sends them
10013
/// first, in parts of objects alone, so no request is larger than about
10014
/// that (a proxy in front of a hub refuses one past 100 MB); the change
10015
/// and the bookmark follow, and a clone has every file.
10016
#[test]
10017
fn a_heavy_change_sends_its_blobs_in_parts() {
10018
    hermetic();
10019
    let dir = tempfile::tempdir().unwrap();
10020
    let root = dir.path();
10021
    let origin = root.join("origin");
10022
    Repo::init_bare_unbound(&origin).unwrap();
10023
    let main = root.join("main");
10024
    let mut repo = Repo::init(&main).unwrap();
10025
    repo.config
10026
        .set("remote.origin.url", &origin.to_string_lossy())
10027
        .unwrap();
10028
    repo.config.set("push.batch-bytes", "50000").unwrap();
10029
    repo.save_config().unwrap();
10030
    let mut x: u64 = 0x9e3779b97f4a7c15;
10031
    let mut noise = |n: usize| -> Vec<u8> {
10032
        (0..n)
10033
            .map(|_| {
10034
                x ^= x << 13;
10035
                x ^= x >> 7;
10036
                x ^= x << 17;
10037
                (x >> 24) as u8
10038
            })
10039
            .collect()
10040
    };
10041
    let files: Vec<Vec<u8>> = (0..4).map(|_| noise(40_000)).collect();
10042
    for (i, f) in files.iter().enumerate() {
10043
        write(&main, &format!("bin{i}.dat"), f);
10044
    }
10045
    repo.commit("four blobs", &[]).unwrap();
10046
    let mut parts = Vec::new();
10047
    let results = repo
10048
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
10049
        .unwrap();
10050
    assert!(
10051
        results.iter().any(|r| r.ok && r.name == "main"),
10052
        "{results:?}"
10053
    );
10054
    assert!(
10055
        parts.len() >= 3 && parts[0].starts_with("objects 1 of"),
10056
        "{parts:?}"
10057
    );
10058
    let back = Repo::clone(&origin.to_string_lossy(), &root.join("back")).unwrap();
10059
    for (i, f) in files.iter().enumerate() {
10060
        assert_eq!(&fs::read(root.join(format!("back/bin{i}.dat"))).unwrap(), f);
10061
    }
10062
    drop(back);
10063
}
10064
10065
/// oxygen#97: with `git.claim`, an import authors the importing identity's
10066
/// own commits (Git author email = its email, any case) with its key, and
10067
/// leaves anyone else's with the zero key; the history verifies as before.
10068
#[test]
10069
fn git_import_claims_your_own_commits() {
10070
    hermetic();
10071
    if std::process::Command::new("git")
10072
        .arg("--version")
10073
        .output()
10074
        .is_err()
10075
    {
10076
        eprintln!("git not installed; skipping");
10077
        return;
10078
    }
10079
    let dir = tempfile::tempdir().unwrap();
10080
    let root = dir.path();
10081
    let g = root.join("src.git");
10082
    fs::create_dir_all(&g).unwrap();
10083
    let git = |who: &str, args: &[&str]| {
10084
        let (name, email) = who.split_once(' ').unwrap();
10085
        let out = std::process::Command::new("git")
10086
            .arg("-C")
10087
            .arg(&g)
10088
            .args([
10089
                "-c",
10090
                &format!("user.name={name}"),
10091
                "-c",
10092
                &format!("user.email={email}"),
10093
                "-c",
10094
                "commit.gpgsign=false",
10095
            ])
10096
            .args(args)
10097
            .output()
10098
            .unwrap();
10099
        assert!(
10100
            out.status.success(),
10101
            "git {args:?}: {}",
10102
            String::from_utf8_lossy(&out.stderr)
10103
        );
10104
    };
10105
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
10106
    write(&g, "a.txt", b"a\n");
10107
    git("Grace [email protected]", &["add", "."]);
10108
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
10109
    write(&g, "b.txt", b"b\n");
10110
    git("Ada [email protected]", &["add", "."]);
10111
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
10112
10113
    let mut repo = Repo::init(&root.join("o")).unwrap();
10114
    let (key, _) = repo
10115
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
10116
        .unwrap();
10117
    repo.config.set("git.claim", "true").unwrap();
10118
    repo.save_config().unwrap();
10119
    let repo = Repo::open(&root.join("o")).unwrap();
10120
    repo.import_git(&g, "main").unwrap();
10121
    let v = repo.verify_git_import(&g, "main").unwrap();
10122
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
10123
    let heads = repo.bookmark_heads().unwrap();
10124
    let by_message: std::collections::HashMap<String, KeyId> = repo
10125
        .log_state(&heads)
10126
        .unwrap()
10127
        .into_iter()
10128
        .map(|e| {
10129
            (
10130
                e.change.message.lines().next().unwrap_or("").to_string(),
10131
                e.change.author,
10132
            )
10133
        })
10134
        .collect();
10135
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
10136
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
10137
}
10138
10139
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
10140
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
10141
#[test]
10142
fn removing_a_remote_leaves_nothing_of_it() {
10143
    hermetic();
10144
    let dir = tempfile::tempdir().unwrap();
10145
    let origin = dir.path().join("origin");
10146
    Repo::init_bare_unbound(&origin).unwrap();
10147
    let main = dir.path().join("main");
10148
    let mut repo = Repo::init(&main).unwrap();
10149
    repo.config
10150
        .set("remote.origin.url", &origin.to_string_lossy())
10151
        .unwrap();
10152
    repo.config
10153
        .set("remote.origin.token", "secret-ish")
10154
        .unwrap();
10155
    repo.config
10156
        .set("remote.keep.url", &origin.to_string_lossy())
10157
        .unwrap();
10158
    repo.save_config().unwrap();
10159
    write(&main, "a.txt", b"a\n");
10160
    repo.commit("a", &[]).unwrap();
10161
    assert!(repo.push("origin", false).unwrap()[0].ok);
10162
    assert!(
10163
        repo.view().unwrap().remotes.contains_key("origin"),
10164
        "a tracking bookmark"
10165
    );
10166
10167
    repo.remove_remote("origin").unwrap();
10168
    let again = Repo::open(&main).unwrap();
10169
    assert!(
10170
        !again
10171
            .config
10172
            .repo_layer()
10173
            .keys()
10174
            .any(|k| k.starts_with("remote.origin.")),
10175
        "{:?}",
10176
        again.config.repo_layer()
10177
    );
10178
    assert!(!again.config.remotes.contains_key("origin"));
10179
    assert!(
10180
        !again.view().unwrap().remotes.contains_key("origin"),
10181
        "its tracking bookmarks go"
10182
    );
10183
    assert!(
10184
        again.config.remotes.contains_key("keep"),
10185
        "another remote stays"
10186
    );
10187
    let mut again = again;
10188
    assert!(
10189
        again.remove_remote("origin").is_err(),
10190
        "a second removal is refused"
10191
    );
10192
}
10193
10194
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
10195
/// unreachable from history, so gc prunes it, unless the host names it:
10196
/// then it and its chunks stay, and it reads back whole.
10197
#[test]
10198
fn gc_keeps_the_blobs_a_host_names() {
10199
    hermetic();
10200
    let dir = tempfile::tempdir().unwrap();
10201
    let repo = Repo::init(dir.path()).unwrap();
10202
    write(dir.path(), "a.txt", b"a\n");
10203
    repo.commit("a", &[]).unwrap();
10204
    // Large enough to be several chunks.
10205
    let body: Vec<u8> = (0..400_000u32)
10206
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
10207
        .collect();
10208
    let kept = repo.store_blob(&body).unwrap();
10209
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
10210
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
10211
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
10212
    assert!(!repo.store().has(&lost), "not named: pruned");
10213
    repo.gc(true).unwrap();
10214
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
10215
}
10216
10217
/// oxygen#99: undo in one workspace undoes that workspace's last command,
10218
/// never another workspace's, says what it undid, and goes further back
10219
/// when run again.
10220
#[test]
10221
fn undo_is_scoped_to_its_workspace() {
10222
    hermetic();
10223
    let dir = tempfile::tempdir().unwrap();
10224
    let root = dir.path().join("main");
10225
    let a = Repo::init(&root).unwrap();
10226
    write(&root, "base.txt", b"base\n");
10227
    let base = a.commit("base", &[]).unwrap();
10228
    a.bookmark_create("feature", None).unwrap();
10229
    let ws_dir = dir.path().join("ws");
10230
    let heads = a.resolve_heads("feature").unwrap();
10231
    let b = a
10232
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
10233
        .unwrap();
10234
10235
    // A commits on main, then B commits on feature: B's is the newest.
10236
    write(&root, "a.txt", b"a\n");
10237
    let ca = a.commit("from a", &[]).unwrap();
10238
    write(&ws_dir, "b.txt", b"b\n");
10239
    let cb = b.commit("from b", &[]).unwrap();
10240
10241
    // A's undo undoes A's commit and leaves B's.
10242
    let u = a.undo().unwrap();
10243
    assert_eq!(u.command, "oxy commit -m \"from a\"");
10244
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
10245
    assert!(!u.changes.is_empty());
10246
    let view = a.view().unwrap();
10247
    // (Independent changes commute, so a bookmark's heads may hold base too.)
10248
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
10249
    assert!(
10250
        a.heads_of(&view, "feature").unwrap().contains(&cb),
10251
        "B's commit stands"
10252
    );
10253
    assert!(
10254
        a.store().get_change(&ca).is_ok(),
10255
        "the change itself is still in the store"
10256
    );
10257
    // A's working copy was clean, so its files followed; B's are untouched.
10258
    assert!(!root.join("a.txt").exists());
10259
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
10260
    assert!(ws_dir.join("b.txt").exists());
10261
10262
    // B's undo still finds B's own commit, under A's undo.
10263
    let u = b.undo().unwrap();
10264
    assert_eq!(u.command, "oxy commit -m \"from b\"");
10265
    assert!(!b
10266
        .heads_of(&b.view().unwrap(), "feature")
10267
        .unwrap()
10268
        .contains(&cb));
10269
    assert_eq!(
10270
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
10271
        vec![base],
10272
        "A's undo stands"
10273
    );
10274
10275
    // A's next undo goes past the commit it already undid, to adding B's
10276
    // workspace: refused, since B has worked there since.
10277
    let e = a.undo().unwrap_err().to_string();
10278
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
10279
}
10280
10281
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
10282
/// own commit's head, and the other workspace's head stays.
10283
#[test]
10284
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
10285
    hermetic();
10286
    let dir = tempfile::tempdir().unwrap();
10287
    let root = dir.path().join("main");
10288
    let a = Repo::init(&root).unwrap();
10289
    write(&root, "base.txt", b"base\n");
10290
    a.commit("base", &[]).unwrap();
10291
    let ws_dir = dir.path().join("ws");
10292
    let b = a.workspace_add(&ws_dir, None).unwrap();
10293
    write(&root, "a.txt", b"a\n");
10294
    let ca = a.commit("from a", &[]).unwrap();
10295
    write(&ws_dir, "b.txt", b"b\n");
10296
    let cb = b.commit("from b", &[]).unwrap();
10297
    let u = a.undo().unwrap();
10298
    assert_eq!(u.command, "oxy commit -m \"from a\"");
10299
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
10300
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
10301
}
10302
10303
/// oxygen#99: an undo that would also take back what another workspace
10304
/// did since to the same bookmark is refused, naming it.
10305
#[test]
10306
fn undo_refuses_to_take_back_another_workspaces_work() {
10307
    hermetic();
10308
    let dir = tempfile::tempdir().unwrap();
10309
    let root = dir.path().join("main");
10310
    let a = Repo::init(&root).unwrap();
10311
    write(&root, "base.txt", b"base\n");
10312
    a.commit("base", &[]).unwrap();
10313
    let ws_dir = dir.path().join("ws");
10314
    let b = a.workspace_add(&ws_dir, None).unwrap();
10315
    // Both on main: A commits, then B builds on it, editing A's file.
10316
    write(&root, "a.txt", b"a\n");
10317
    a.commit("from a", &[]).unwrap();
10318
    b.refresh().unwrap();
10319
    let heads = b.resolve_heads("main").unwrap();
10320
    b.checkout(&heads, false, "oxy checkout").unwrap();
10321
    write(&ws_dir, "a.txt", b"a, then b\n");
10322
    b.commit("from b", &[]).unwrap();
10323
    let e = a.undo().unwrap_err().to_string();
10324
    assert!(
10325
        e.contains("bookmark main") && e.contains("builds on"),
10326
        "{e}"
10327
    );
10328
    assert!(e.contains("oxy op restore"), "{e}");
10329
}
10330
10331
/// oxygen#99: undoing a commit that was already pushed says so: the remote
10332
/// still has it.
10333
#[test]
10334
fn undo_says_when_the_commit_was_pushed() {
10335
    hermetic();
10336
    let dir = tempfile::tempdir().unwrap();
10337
    let root = dir.path();
10338
    Repo::init(&root.join("origin")).unwrap();
10339
    let url = root.join("origin").to_string_lossy().to_string();
10340
    let repo = Repo::clone(&url, &root.join("work"))
10341
        .unwrap()
10342
        .with_home(root.join("home"));
10343
    write(&root.join("work"), "a.txt", b"a\n");
10344
    repo.commit("a", &[]).unwrap();
10345
    assert!(repo.push("origin", false).unwrap()[0].ok);
10346
    // The push itself is passed over: the remote keeps what it was sent.
10347
    let u = repo.undo().unwrap();
10348
    assert_eq!(u.command, "oxy commit -m \"a\"");
10349
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
10350
}
10351
10352
/// oxygen#98: a new untracked file over snapshot.max-new-file-size is left
10353
/// out of the snapshot and named; tracked files and files already in the
10354
/// working copy are not.
10355
#[test]
10356
fn large_new_files_are_left_out_of_snapshots() {
10357
    hermetic();
10358
    let dir = tempfile::tempdir().unwrap();
10359
    let root = dir.path();
10360
    let mut repo = Repo::init(root).unwrap();
10361
    repo.config.max_new_file = 1024;
10362
    write(root, "small.txt", b"small\n");
10363
    write(root, "big.bin", &vec![0u8; 4096]);
10364
    let s = repo.snapshot("oxy status").unwrap();
10365
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
10366
    assert_eq!(paths, ["small.txt"]);
10367
    assert_eq!(repo.skipped_large(), vec![("big.bin".to_string(), 4096)]);
10368
    repo.commit("small", &[]).unwrap();
10369
10370
    // A tracked file may grow past the limit.
10371
    write(root, "small.txt", &vec![b'x'; 4096]);
10372
    let s = repo.snapshot("oxy status").unwrap();
10373
    assert!(s.statuses.iter().any(|p| p.path == "small.txt"));
10374
    // With no limit the big file is taken in, and stays once it is.
10375
    repo.config.max_new_file = 0;
10376
    let s = repo.snapshot("oxy status").unwrap();
10377
    assert!(s.statuses.iter().any(|p| p.path == "big.bin"));
10378
    repo.config.max_new_file = 1024;
10379
    let s = repo.snapshot("oxy status").unwrap();
10380
    assert!(
10381
        s.statuses.iter().any(|p| p.path == "big.bin"),
10382
        "already in the working copy"
10383
    );
10384
    assert!(repo.skipped_large().is_empty());
10385
}
10386
10387
/// oxygen#98: a file only a past working-copy snapshot held is pruned once
10388
/// snapshots expire, and kept while they have not.
10389
#[test]
10390
fn gc_prunes_what_only_expired_snapshots_held() {
10391
    hermetic();
10392
    let dir = tempfile::tempdir().unwrap();
10393
    let root = dir.path();
10394
    let mut repo = Repo::init(root).unwrap();
10395
    repo.config.gc_grace_days = 0;
10396
    write(root, "a.txt", b"a\n");
10397
    repo.commit("a", &[]).unwrap();
10398
    let image: Vec<u8> = (0..200_000u32).map(|i| (i % 7) as u8).collect();
10399
    write(root, "image.tar", &image);
10400
    repo.snapshot("oxy status").unwrap();
10401
    std::fs::remove_file(root.join("image.tar")).unwrap();
10402
    repo.snapshot("oxy status").unwrap();
10403
    let blob = Repo::blob_ref(&image);
10404
    assert!(repo.store().has(&blob));
10405
    repo.gc(true).unwrap();
10406
    assert!(repo.store().has(&blob), "a recent snapshot keeps it");
10407
    repo.config.snapshot_retention_days = 0;
10408
    repo.gc(true).unwrap();
10409
    assert!(!repo.store().has(&blob), "an expired snapshot does not");
10410
    assert_eq!(
10411
        repo.file_at("a.txt", None).unwrap(),
10412
        b"a\n",
10413
        "committed files stay"
10414
    );
10415
}
10416
10417
/// oxygen#100: uncommitted work byte-for-byte what the bookmark switched to
10418
/// already has is no conflict: the switch goes through, nothing is lost,
10419
/// and other carried work still comes along.
10420
#[test]
10421
fn carrying_work_the_target_already_has_is_no_conflict() {
10422
    hermetic();
10423
    let dir = tempfile::tempdir().unwrap();
10424
    let root = dir.path();
10425
    let mut repo = Repo::init(root).unwrap();
10426
    write(root, "a.txt", b"one\n");
10427
    write(root, "b.txt", b"b\n");
10428
    repo.commit("one", &[]).unwrap();
10429
    repo.bookmark_create("landed", None).unwrap();
10430
    // On landed, a.txt becomes "two" (as a proposal landing would).
10431
    repo.bookmark_switch("landed", false).unwrap();
10432
    write(root, "a.txt", b"two\n");
10433
    repo.commit("two", &[]).unwrap();
10434
    repo.bookmark_switch("main", false).unwrap();
10435
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"one\n");
10436
    // The same edit, uncommitted, on main; and another edit besides.
10437
    write(root, "a.txt", b"two\n");
10438
    write(root, "b.txt", b"b, edited\n");
10439
    let (_, carried) = repo.bookmark_switch_carry("landed").unwrap();
10440
    assert_eq!(
10441
        carried,
10442
        vec!["b.txt".to_string()],
10443
        "only the work landed lacks is carried"
10444
    );
10445
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"two\n");
10446
    assert_eq!(std::fs::read(root.join("b.txt")).unwrap(), b"b, edited\n");
10447
    let s = repo.snapshot("oxy status").unwrap();
10448
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
10449
    assert_eq!(paths, ["b.txt"]);
10450
10451
    // A real difference is still refused.
10452
    repo.bookmark_switch("main", true).unwrap();
10453
    write(root, "a.txt", b"three\n");
10454
    let e = repo
10455
        .bookmark_switch_carry("landed")
10456
        .unwrap_err()
10457
        .to_string();
10458
    assert!(e.contains("a.txt") && e.contains("--discard"), "{e}");
10459
}
10460
10461
/// oxygen#103: a full change hash as `--json` prints it, without `#`,
10462
/// resolves, so JSON output feeds back into commands.
10463
#[test]
10464
fn a_full_hash_resolves_without_its_hash_sign() {
10465
    hermetic();
10466
    let dir = tempfile::tempdir().unwrap();
10467
    let root = dir.path();
10468
    let repo = Repo::init(root).unwrap();
10469
    write(root, "a.txt", b"a\n");
10470
    let h = repo.commit("a", &[]).unwrap();
10471
    assert_eq!(repo.resolve_change(&h.to_hex()).unwrap(), h);
10472
    assert_eq!(repo.resolve_change(&format!("#{}", h.to_hex())).unwrap(), h);
10473
    assert!(repo
10474
        .resolve_change(&"0".repeat(64))
10475
        .unwrap_err()
10476
        .to_string()
10477
        .contains("no change matches"));
10478
}
10479
10480
#[test]
10481
fn a_pin_change_moves_only_the_pin() {
10482
    hermetic();
10483
    let dir = tempfile::tempdir().unwrap();
10484
    let root = dir.path();
10485
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
10486
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
10487
    let lib = Repo::clone(&lib_url, &root.join("lib"))
10488
        .unwrap()
10489
        .with_home(root.join("home"));
10490
    write(&root.join("lib"), "lib.txt", b"v1\n");
10491
    lib.commit("lib v1", &[]).unwrap();
10492
    assert!(lib.push("origin", false).unwrap()[0].ok);
10493
    let _app_origin = Repo::init(&root.join("app-origin")).unwrap();
10494
    let app_dir = root.join("app");
10495
    let app = Repo::clone(&root.join("app-origin").to_string_lossy(), &app_dir)
10496
        .unwrap()
10497
        .with_home(root.join("home"));
10498
    write(&app_dir, "main.txt", b"app\n");
10499
    let pin1 = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
10500
    let a1 = app.commit("app with lib", &[]).unwrap();
10501
    // The library moves on.
10502
    write(&root.join("lib"), "more.txt", b"v2\n");
10503
    let l2 = lib.commit("lib v2", &[]).unwrap();
10504
    let crate::subrepo::Pin::Oxy { repo, bookmark, .. } = pin1 else {
10505
        panic!("an Oxygen pin")
10506
    };
10507
    let pin2 = crate::subrepo::Pin::Oxy {
10508
        repo,
10509
        heads: vec![l2],
10510
        bookmark,
10511
    };
10512
    let author = app.store().get_change(&a1).unwrap().author;
10513
    let change = app
10514
        .build_pin_change(&[a1], "libs/lib", &pin2, "Move lib to v2", author)
10515
        .unwrap();
10516
    let mut state = app.load_state(&[a1]).unwrap();
10517
    state.add(change).unwrap();
10518
    let files = state.materialize().files;
10519
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
10520
    let FileContent::Opaque { blobs } = &files["libs/lib"].content else {
10521
        panic!("a pin is opaque")
10522
    };
10523
    let read = crate::subrepo::Pin::decode(&app.read_blob(&blobs[0]).unwrap()).unwrap();
10524
    assert_eq!(read, pin2, "the new pin");
10525
    assert!(
10526
        matches!(&files["main.txt"].content, FileContent::Text { bytes, .. } if bytes.as_slice() == b"app\n"),
10527
        "nothing else changes"
10528
    );
10529
    // Only a subrepo's pin can be moved this way.
10530
    let e = app.build_pin_change(&[a1], "main.txt", &pin2, "x", author);
10531
    assert!(format!("{:?}", e.unwrap_err()).contains("not a subrepo"));
10532
    let e = app.build_pin_change(&[a1], "libs/none", &pin2, "x", author);
10533
    assert!(format!("{:?}", e.unwrap_err()).contains("does not exist"));
10534
}
10535
10536
/// oxygenhub#249: a handle reads the operation head once and keeps it,
10537
/// so one command or request never mixes two heads; another handle's
10538
/// operation shows only after `refresh`. Its own operations move it, and
10539
/// one recorded from the head it kept merges with what landed since, as
10540
/// any concurrent operation does.
10541
#[test]
10542
fn one_handle_keeps_one_head_until_it_refreshes() {
10543
    hermetic();
10544
    let dir = tempfile::tempdir().unwrap();
10545
    let root = dir.path();
10546
    let writer = Repo::init(root).unwrap();
10547
    write(root, "a.txt", b"one\n");
10548
    let h1 = writer.commit("one", &[]).unwrap();
10549
    let reader = Repo::open(root).unwrap();
10550
    let before = reader.view().unwrap();
10551
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
10552
    write(root, "a.txt", b"two\n");
10553
    let h2 = writer.commit("two", &[]).unwrap();
10554
    assert_eq!(
10555
        writer.bookmark_heads().unwrap(),
10556
        vec![h2],
10557
        "its own operation"
10558
    );
10559
    assert_eq!(reader.view().unwrap(), before, "the head it read first");
10560
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
10561
    reader.refresh().unwrap();
10562
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h2]);
10563
10564
    // A handle recording from an older head merges with the newer one.
10565
    let stale = Repo::open(root).unwrap();
10566
    assert_eq!(stale.bookmark_heads().unwrap(), vec![h2]);
10567
    write(root, "a.txt", b"three\n");
10568
    let h3 = writer.commit("three", &[]).unwrap();
10569
    stale.bookmark_create("feature", Some(&[h1])).unwrap();
10570
    let view = stale.view().unwrap();
10571
    assert!(view.bookmarks.contains_key("feature"));
10572
    assert_eq!(
10573
        stale.bookmark_heads().unwrap(),
10574
        vec![h3],
10575
        "merged, not lost"
10576
    );
10577
    let fresh = Repo::open(root).unwrap();
10578
    assert_eq!(fresh.view().unwrap(), view);
10579
}
10580
10581
/// oxygenhub#249 over a store (a bucket's compare-and-swap): the same.
10582
#[test]
10583
fn over_a_store_one_handle_keeps_one_head() {
10584
    hermetic();
10585
    let backend = std::sync::Arc::new(crate::strata::MemoryStore::new());
10586
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
10587
    let dir = tempfile::tempdir().unwrap();
10588
    let a = Repo::init(dir.path()).unwrap();
10589
    let (h0, _) = a.head_op().unwrap();
10590
    let b = Repo::open(dir.path()).unwrap();
10591
    assert_eq!(b.head_op().unwrap().0, h0);
10592
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
10593
    let mut view = a.view().unwrap();
10594
    view.bookmarks.insert("x".into(), state);
10595
    let r = a.record_op(&[h0], "bookmark x", view).unwrap();
10596
    assert_eq!(a.head_op().unwrap().0, r);
10597
    assert_eq!(b.head_op().unwrap().0, h0, "b keeps its head");
10598
    b.refresh().unwrap();
10599
    assert_eq!(b.head_op().unwrap().0, r);
10600
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
10601
}
10602
10603
/// oxygenhub#249: gc retires what it repacks rather than deleting it; a
10604
/// reader opened before reads on, then and after the next gc deletes the
10605
/// retired files once their hour is up. Younger ones are kept.
10606
#[test]
10607
fn gc_retires_and_a_later_gc_deletes_after_the_hour() {
10608
    hermetic();
10609
    let dir = tempfile::tempdir().unwrap();
10610
    let root = dir.path();
10611
    let repo = Repo::init(root).unwrap();
10612
    let mut heads = Vec::new();
10613
    for i in 0..4 {
10614
        write(root, &format!("f{i}.txt"), format!("{i}\n").as_bytes());
10615
        heads.push(repo.commit(&format!("c{i}"), &[]).unwrap());
10616
    }
10617
    let reader = Repo::open(root).unwrap();
10618
    assert_eq!(reader.log().unwrap().len(), 5);
10619
    let r = repo.gc(true).unwrap();
10620
    assert_eq!(r.retired, crate::store::RetiredReport::default());
10621
    assert_eq!(repo.store().loose_count().unwrap(), 0);
10622
    assert_eq!(reader.log().unwrap().len(), 5, "read on from what it had");
10623
    // Nothing is an hour old yet: a gc keeps it all.
10624
    let r = repo.gc(true).unwrap();
10625
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
10626
    assert!(r.retired.kept > 0, "{r:?}");
10627
    write(root, "f9.txt", b"9\n");
10628
    heads.push(repo.commit("c9", &[]).unwrap());
10629
    crate::store::reader_tests::age_retired(
10630
        repo.store(),
10631
        crate::store::RETIRED_FOR + std::time::Duration::from_secs(60),
10632
    );
10633
    let r = repo.gc(true).unwrap();
10634
    assert!(r.retired.packs >= 1 && r.retired.loose > 0, "{r:?}");
10635
    assert_eq!(r.retired.kept, 0, "{r:?}");
10636
    let r = repo.gc(true).unwrap();
10637
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
10638
    assert!(r.retired.kept > 0, "what the last gc retired is young");
10639
    // The reader opened before all of it still reads everything, from
10640
    // the packs it finds when what it loaded is gone.
10641
    assert_eq!(reader.log().unwrap().len(), 5);
10642
    for h in &heads[..4] {
10643
        reader.store().get_change(h).unwrap();
10644
    }
10645
    reader.refresh().unwrap();
10646
    assert_eq!(reader.log().unwrap().len(), 6);
10647
    let fresh = Repo::open(root).unwrap();
10648
    assert_eq!(
10649
        fresh.store().pack_count(),
10650
        1,
10651
        "retired packs are not loaded"
10652
    );
10653
}
10654
10655
/// oxygenhub#249: a repository opens when its store's pack listing names
10656
/// an index that is not there (deleted between the listing and the read).
10657
#[test]
10658
fn a_repository_opens_when_a_listed_index_is_gone() {
10659
    hermetic();
10660
    let backend = crate::store::reader_tests::racing(true);
10661
    let dyn_backend: std::sync::Arc<crate::store::Backend> = backend.clone();
10662
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(dyn_backend));
10663
    let dir = tempfile::tempdir().unwrap();
10664
    let repo = Repo::init(dir.path()).unwrap();
10665
    write(dir.path(), "a.txt", b"a\n");
10666
    let h = repo.commit("a", &[]).unwrap();
10667
    repo.gc(true).unwrap();
10668
    let again = Repo::open(dir.path()).unwrap();
10669
    assert_eq!(again.store().pack_count(), 1);
10670
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
10671
    // And when one is deleted between the listing and the read: a copy of
10672
    // the live pack, whose index goes as the store opens.
10673
    use crate::strata::Store as _;
10674
    let idx = backend
10675
        .list("pack-")
10676
        .unwrap()
10677
        .into_iter()
10678
        .map(|e| e.key)
10679
        .find(|k| k.ends_with(".idx") && k != "pack-0000.idx")
10680
        .unwrap();
10681
    let stem = idx.trim_end_matches(".idx");
10682
    for ext in ["pack", "idx"] {
10683
        let bytes = backend.get(&format!("{stem}.{ext}")).unwrap();
10684
        backend
10685
            .put_new(&format!("pack-copy.{ext}"), &bytes)
10686
            .unwrap();
10687
    }
10688
    *backend.doomed.lock().unwrap() = Some("pack-copy.idx".into());
10689
    let again = Repo::open(dir.path()).unwrap();
10690
    assert_eq!(again.store().pack_count(), 1);
10691
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
10692
    assert!(!backend.has("pack-copy.idx").unwrap());
10693
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
10694
}