OXYGENHUB
# c2e1d09047db oxygen / crates / oxy-core / src / repo / tests.rs
311.7 KiB · Rust · last changed The same file added on both sides, identically, is one file 18 days ago source blame history raw
1
//! Tests for the repository layer.
2
3
use super::*;
4
use crate::protocol::SignedPolicy;
5
use crate::repo::{BisectStep, Selection};
6
7
/// Point `$OXY_HOME` at a throwaway directory once per test process so no
8
/// test reads or writes the developer's real user configuration or keys.
9
fn hermetic() {
10
    static ONCE: std::sync::Once = std::sync::Once::new();
11
    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
12
    ONCE.call_once(|| {
13
        let d = tempfile::tempdir().unwrap();
14
        std::env::set_var("OXY_HOME", d.path());
15
        DIR.set(d).ok();
16
    });
17
}
18
19
fn write(root: &Path, rel: &str, content: &[u8]) {
20
    let p = root.join(rel);
21
    fs::create_dir_all(p.parent().unwrap()).unwrap();
22
    fs::write(p, content).unwrap();
23
}
24
25
fn statuses(s: &SnapshotResult) -> Vec<(String, ChangeStatus)> {
26
    s.statuses
27
        .iter()
28
        .map(|p| (p.path.clone(), p.status))
29
        .collect()
30
}
31
32
#[test]
33
fn init_snapshot_commit_log_undo() {
34
    hermetic();
35
    let dir = tempfile::tempdir().unwrap();
36
    let root = dir.path();
37
    let repo = Repo::init(root).unwrap();
38
    assert!(Repo::init(root).is_err());
39
    let ops = repo.op_log().unwrap();
40
    assert_eq!(ops.len(), 1);
41
    assert_eq!(ops[0].1.command, "oxy init");
42
43
    // Empty working copy: snapshot records no operation (spec §12.3).
44
    let s = repo.snapshot("oxy status").unwrap();
45
    assert!(!s.changed);
46
    assert_eq!(repo.op_log().unwrap().len(), 1);
47
48
    write(root, "src/main.rs", b"fn main() {}\n");
49
    write(root, "README.md", b"# Hello\n");
50
    write(root, ".oxyignore", b"/target\n");
51
    write(root, "target/junk.o", b"\0\0\0");
52
    let s = repo.snapshot("oxy status").unwrap();
53
    assert!(s.changed);
54
    assert_eq!(
55
        statuses(&s),
56
        vec![
57
            (".oxyignore".into(), ChangeStatus::Added),
58
            ("README.md".into(), ChangeStatus::Added),
59
            ("src/main.rs".into(), ChangeStatus::Added),
60
        ]
61
    );
62
    assert_eq!(repo.op_log().unwrap().len(), 2);
63
    // Snapshotting again with nothing changed records no op.
64
    let s2 = repo.snapshot("oxy status").unwrap();
65
    assert!(!s2.changed);
66
    assert_eq!(s2.wc_hash, s.wc_hash);
67
    assert_eq!(repo.op_log().unwrap().len(), 2);
68
69
    let h1 = repo.commit("Initial import", &[]).unwrap();
70
    let c1 = repo.store().get_change(&h1).unwrap();
71
    assert_eq!(c1.kind, ChangeKind::Normal);
72
    assert!(c1.deps.is_empty(), "first change has nothing to depend on");
73
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
74
    let (wc_hash, wc) = repo.working_copy().unwrap();
75
    assert_eq!(wc.deps, vec![h1]);
76
    assert!(wc.edits.is_empty());
77
    assert!(repo.commit("nothing", &[]).is_err());
78
79
    // Modify one file, remove another, add a binary file.
80
    write(
81
        root,
82
        "src/main.rs",
83
        b"fn main() {\n    println!(\"hi\");\n}\n",
84
    );
85
    fs::remove_file(root.join("README.md")).unwrap();
86
    write(root, "logo.png", b"\x89PNG\0\0\x01");
87
    let s = repo.snapshot("oxy status").unwrap();
88
    assert_eq!(
89
        statuses(&s),
90
        vec![
91
            ("README.md".into(), ChangeStatus::Removed),
92
            ("logo.png".into(), ChangeStatus::Added),
93
            ("src/main.rs".into(), ChangeStatus::Modified),
94
        ]
95
    );
96
    assert_ne!(s.wc_hash, wc_hash);
97
    // The rewritten working copy keeps its ChangeId and depends on h1.
98
    assert_eq!(s.wc.change_id, wc.change_id);
99
    assert!(s.wc.deps.contains(&h1));
100
101
    let h2 = repo.commit("Second", &[]).unwrap();
102
    let c2 = repo.store().get_change(&h2).unwrap();
103
    assert_eq!(
104
        c2.deps,
105
        vec![h1],
106
        "everything it touches was introduced by h1"
107
    );
108
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
109
110
    // The materialized head state matches the working copy.
111
    let st = repo.load_state(&[h2]).unwrap();
112
    let snap = st.materialize();
113
    assert!(!snap.is_conflicted());
114
    assert_eq!(
115
        snap.files.keys().cloned().collect::<Vec<_>>(),
116
        [".oxyignore", "logo.png", "src", "src/main.rs"]
117
    );
118
    assert!(
119
        matches!(&snap.files["src/main.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn main() {\n    println!(\"hi\");\n}\n")
120
    );
121
    assert!(snap.files["logo.png"].mode.opaque);
122
    if let FileContent::Opaque { blobs } = &snap.files["logo.png"].content {
123
        assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\x89PNG\0\0\x01");
124
    } else {
125
        panic!("logo should be opaque");
126
    }
127
128
    // Log: newest first, working copy included.
129
    let log = repo.log().unwrap();
130
    assert_eq!(log.len(), 3);
131
    assert!(log[0].is_working_copy);
132
    assert_eq!(log[1].hash, h2);
133
    assert!(log[1].is_head);
134
    assert_eq!(log[2].hash, h1);
135
    let d = repo.describe_change(&h2).unwrap();
136
    assert!(d.contains("D README.md"), "{d}");
137
    assert!(d.contains("+    println!(\"hi\");"), "{d}");
138
    assert!(d.contains("-fn main() {}"), "{d}");
139
140
    // Resolution by prefix.
141
    assert_eq!(repo.resolve_change(&c2.change_id.short(6)).unwrap(), h2);
142
    assert_eq!(
143
        repo.resolve_change(&format!("#{}", h1.short(8))).unwrap(),
144
        h1
145
    );
146
    assert!(repo.resolve_change("zzzz").is_err());
147
148
    // Undo the commit: bookmark and working copy go back.
149
    repo.undo().unwrap();
150
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
151
    let s = repo.snapshot("oxy status").unwrap();
152
    assert!(
153
        !s.changed,
154
        "files on disk still match the pre-commit working copy"
155
    );
156
    assert_eq!(s.statuses.len(), 3);
157
}
158
159
/// Make `main` conflicted: two commits on the same base that edit the same line.
160
fn conflicted_repo() -> (tempfile::TempDir, Repo, ChangeHash, ChangeHash, ChangeHash) {
161
    let dir = tempfile::tempdir().unwrap();
162
    let root = dir.path();
163
    let repo = Repo::init(root).unwrap();
164
    write(root, "f.txt", b"a\nb\nc\n");
165
    let h1 = repo.commit("base", &[]).unwrap();
166
    write(root, "f.txt", b"a\nB\nc\n");
167
    let h2 = repo.commit("upper", &[]).unwrap();
168
    repo.checkout(&[h1], false, "checkout").unwrap();
169
    write(root, "f.txt", b"a\nX\nc\n");
170
    let h3 = repo.commit("ex", &[]).unwrap();
171
    (dir, repo, h1, h2, h3)
172
}
173
174
#[test]
175
fn concurrent_edits_conflict_and_can_be_resolved() {
176
    hermetic();
177
    let (dir, repo, h1, h2, h3) = conflicted_repo();
178
    let root = dir.path();
179
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
180
    assert_eq!(heads, [h2, h3].into_iter().collect());
181
    let st = repo.load_state(&[h2, h3]).unwrap();
182
    assert!(st.materialize().is_conflicted());
183
184
    // Checking out main writes markers.
185
    let r = repo
186
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
187
        .unwrap();
188
    assert!(r.conflicted);
189
    let marked = fs::read_to_string(root.join("f.txt")).unwrap();
190
    assert!(
191
        marked.starts_with("a\n<<<<<<< oxy conflict 1 of 1"),
192
        "{marked}"
193
    );
194
    assert!(
195
        marked.contains("B\n") && marked.contains("X\n") && marked.ends_with("end\nc\n"),
196
        "{marked}"
197
    );
198
    assert!(has_conflict_markers(marked.as_bytes()));
199
    // Untouched markers: clean working copy; commit has nothing to do.
200
    let s = repo.snapshot("status").unwrap();
201
    assert!(s.statuses.is_empty());
202
    assert!(!s.resolves);
203
204
    // Partially edited file that still has markers cannot be committed.
205
    write(root, "f.txt", marked.replace("B\n", "BB\n").as_bytes());
206
    let s = repo.snapshot("status").unwrap();
207
    assert_eq!(
208
        statuses(&s),
209
        vec![("f.txt".into(), ChangeStatus::ConflictEdited)]
210
    );
211
    assert!(repo.commit("no", &[]).is_err());
212
213
    // Resolve by keeping one side and adding a line elsewhere.
214
    write(root, "f.txt", b"a\nX\nc\nd\n");
215
    let s = repo.snapshot("status").unwrap();
216
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
217
    assert!(s.resolves);
218
    let h4 = repo.commit("resolve", &[]).unwrap();
219
    let c4 = repo.store().get_change(&h4).unwrap();
220
    assert_eq!(c4.kind, ChangeKind::Resolution);
221
    let mut want = vec![h1, h2, h3];
222
    want.sort();
223
    assert_eq!(
224
        c4.deps, want,
225
        "a resolution depends on exactly the contributors and what it references"
226
    );
227
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h4]);
228
    let snap = repo.load_state(&[h4]).unwrap().materialize();
229
    assert!(!snap.is_conflicted());
230
    assert!(
231
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
232
    );
233
    assert!(!repo.snapshot("status").unwrap().changed);
234
    // A peer holding only h2 and h3 and receiving h4 sees the same result,
235
    // whatever order the changes arrive in.
236
    let mut st = State::new();
237
    for h in [h4, h3, h1, h2] {
238
        st.add_unchecked(repo.store().get_change(&h).unwrap());
239
    }
240
    st.validate().unwrap();
241
    assert!(
242
        matches!(&st.materialize().files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
243
    );
244
}
245
246
#[test]
247
fn resolution_may_keep_both_sides_or_neither() {
248
    hermetic();
249
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
250
    let root = dir.path();
251
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
252
        .unwrap();
253
    // Keep both sides in a chosen order.
254
    write(root, "f.txt", b"a\nX\nB\nc\n");
255
    let h = repo.commit("both", &[]).unwrap();
256
    let snap = repo.load_state(&[h]).unwrap().materialize();
257
    assert!(!snap.is_conflicted());
258
    assert!(
259
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n")
260
    );
261
    // Undo and instead drop the whole region.
262
    repo.undo().unwrap();
263
    write(root, "f.txt", b"a\nc\n");
264
    let h = repo.commit("neither", &[]).unwrap();
265
    let snap = repo.load_state(&[h]).unwrap().materialize();
266
    assert!(!snap.is_conflicted());
267
    assert!(
268
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n")
269
    );
270
}
271
272
#[test]
273
fn name_conflict_resolved_by_removing_a_candidate() {
274
    hermetic();
275
    let dir = tempfile::tempdir().unwrap();
276
    let root = dir.path();
277
    let repo = Repo::init(root).unwrap();
278
    write(root, "keep.txt", b"k\n");
279
    let h1 = repo.commit("base", &[]).unwrap();
280
    write(root, "new.txt", b"one\n");
281
    repo.commit("one", &[]).unwrap();
282
    repo.checkout(&[h1], false, "checkout").unwrap();
283
    write(root, "new.txt", b"two\n");
284
    repo.commit("two", &[]).unwrap();
285
    let r = repo
286
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
287
        .unwrap();
288
    assert!(r.conflicted);
289
    assert!(
290
        root.join("new.txt.oxy-conflict-1").exists()
291
            && root.join("new.txt.oxy-conflict-2").exists()
292
    );
293
    assert!(!root.join("new.txt").exists());
294
    // Candidate numbering follows change-hash order, so pick by content:
295
    // keep the "two" candidate under the real name and drop the other.
296
    let (keep, drop) = if fs::read(root.join("new.txt.oxy-conflict-1")).unwrap() == b"two\n" {
297
        (1, 2)
298
    } else {
299
        (2, 1)
300
    };
301
    fs::remove_file(root.join(format!("new.txt.oxy-conflict-{drop}"))).unwrap();
302
    fs::rename(
303
        root.join(format!("new.txt.oxy-conflict-{keep}")),
304
        root.join("new.txt"),
305
    )
306
    .unwrap();
307
    let h = repo.commit("pick two", &[]).unwrap();
308
    assert_eq!(
309
        repo.store().get_change(&h).unwrap().kind,
310
        ChangeKind::Resolution
311
    );
312
    // The resolution does not touch keep.txt, so it does not depend on h1;
313
    // the bookmark keeps both as heads and their union is the state.
314
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
315
    assert_eq!(heads, [h1, h].into_iter().collect());
316
    let snap = repo
317
        .load_state(&repo.bookmark_heads().unwrap())
318
        .unwrap()
319
        .materialize();
320
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
321
    assert_eq!(
322
        snap.files.keys().cloned().collect::<Vec<_>>(),
323
        ["keep.txt", "new.txt"]
324
    );
325
    assert!(
326
        matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n")
327
    );
328
}
329
330
/// Each of two bookmarks adds `path` (a file written by `side` on each)
331
/// from the same base, and the second is merged into the first. Returns
332
/// the repository on `main`, the merge's heads, and the three changes.
333
fn merged_additions(
334
    side: impl Fn(&Path, bool),
335
) -> (tempfile::TempDir, Repo, Vec<ChangeHash>, [ChangeHash; 3]) {
336
    let dir = tempfile::tempdir().unwrap();
337
    let root = dir.path().to_path_buf();
338
    let mut repo = Repo::init(&root).unwrap();
339
    write(&root, "keep.txt", b"k\n");
340
    let h1 = repo.commit("base", &[]).unwrap();
341
    repo.bookmark_create("side", None).unwrap();
342
    side(&root, false);
343
    let ha = repo.commit("add on main", &[]).unwrap();
344
    repo.bookmark_switch("side", false).unwrap();
345
    side(&root, true);
346
    let hb = repo.commit("add on side", &[]).unwrap();
347
    repo.bookmark_switch("main", false).unwrap();
348
    let m = repo.merge("side").unwrap();
349
    assert!(m.changed && m.checked_out);
350
    (dir, repo, m.heads, [h1, ha, hb])
351
}
352
353
fn conflict_copies(root: &Path) -> Vec<String> {
354
    let mut out: Vec<String> = fs::read_dir(root)
355
        .unwrap()
356
        .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
357
        .filter(|n| n.contains(".oxy-conflict-"))
358
        .collect();
359
    out.sort();
360
    out
361
}
362
363
/// The same path added on two bookmarks with identical content is one
364
/// file after the merge (oxygen#101): no conflict, nothing to resolve,
365
/// nothing recorded; and editing or removing it later keeps it one.
366
#[test]
367
fn identical_additions_unify_on_merge() {
368
    hermetic();
369
    let (dir, repo, heads, [h1, ha, hb]) =
370
        merged_additions(|root, _| write(root, "x.txt", b"same\nlines\n"));
371
    let root = dir.path();
372
    // The tree graph has the name conflict; every reader sees one file.
373
    let st = repo.load_state(&heads).unwrap();
374
    assert!(st
375
        .tree()
376
        .view()
377
        .conflicts
378
        .iter()
379
        .any(|c| matches!(c, crate::tree::TreeConflict::Name { .. })));
380
    let snap = st.materialize();
381
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
382
    assert_eq!(
383
        snap.files.keys().cloned().collect::<Vec<_>>(),
384
        ["keep.txt", "x.txt"]
385
    );
386
    assert!(
387
        matches!(&snap.files["x.txt"].content, FileContent::Text { bytes, .. } if bytes == b"same\nlines\n")
388
    );
389
    assert_eq!(snap.tree.unified.len(), 1);
390
    // On disk once, the working copy clean, nothing to commit.
391
    assert_eq!(fs::read(root.join("x.txt")).unwrap(), b"same\nlines\n");
392
    assert!(
393
        conflict_copies(root).is_empty(),
394
        "{:?}",
395
        conflict_copies(root)
396
    );
397
    let s = repo.snapshot("status").unwrap();
398
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
399
    assert!(!s.changed && !s.resolves);
400
    assert!(!s.base_snapshot.is_conflicted());
401
    assert!(s.wc.tree_ops.is_empty() && s.wc.edits.is_empty());
402
    let json = repo.status_json(&s).unwrap();
403
    assert!(json.contains("\"conflicted\":false"), "{json}");
404
    assert!(repo.commit("nothing", &[]).is_err());
405
    assert_eq!(repo.file_at("x.txt", None).unwrap(), b"same\nlines\n");
406
    // A peer holding the same changes, added in another order, agrees.
407
    let mut peer = State::new();
408
    for h in [hb, ha, h1] {
409
        peer.add_unchecked(repo.store().get_change(&h).unwrap());
410
    }
411
    peer.validate().unwrap();
412
    let ps = peer.materialize();
413
    assert!(!ps.is_conflicted());
414
    assert_eq!(ps.tree.entries["x.txt"], snap.tree.entries["x.txt"]);
415
    assert_eq!(ps.tree.unified, snap.tree.unified);
416
    // The file's history is both additions.
417
    let log: Vec<ChangeHash> = repo
418
        .log_for_path("x.txt")
419
        .unwrap()
420
        .iter()
421
        .map(|e| e.hash)
422
        .collect();
423
    assert!(log.contains(&ha) && log.contains(&hb), "{log:?}");
424
425
    // Edited and committed: one file still, the duplicate retired with it.
426
    write(root, "x.txt", b"same\nedited\n");
427
    let s = repo.snapshot("status").unwrap();
428
    assert_eq!(statuses(&s), vec![("x.txt".into(), ChangeStatus::Modified)]);
429
    let he = repo.commit("edit x", &[]).unwrap();
430
    let c = repo.store().get_change(&he).unwrap();
431
    assert_eq!(c.kind, ChangeKind::Normal);
432
    let (dup, _) = snap.tree.unified.iter().next().unwrap();
433
    assert!(
434
        c.tree_ops
435
            .iter()
436
            .any(|o| matches!(o, TreeOp::RemoveNode { node, .. } if node == dup)),
437
        "{:?}",
438
        c.tree_ops
439
    );
440
    let d = repo.describe_change(&he).unwrap();
441
    assert!(!d.contains("D x.txt"), "{d}");
442
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
443
    assert!(
444
        st.tree().view().conflicts.is_empty(),
445
        "nothing left to unify"
446
    );
447
    let snap = st.materialize();
448
    assert!(!snap.is_conflicted());
449
    assert!(
450
        matches!(&snap.files["x.txt"].content, FileContent::Text { bytes, .. } if bytes == b"same\nedited\n")
451
    );
452
    assert!(!repo.snapshot("status").unwrap().changed);
453
454
    // Removed and committed: gone.
455
    fs::remove_file(root.join("x.txt")).unwrap();
456
    repo.commit("drop x", &[]).unwrap();
457
    let snap = repo
458
        .load_state(&repo.bookmark_heads().unwrap())
459
        .unwrap()
460
        .materialize();
461
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
462
    assert_eq!(snap.files.keys().cloned().collect::<Vec<_>>(), ["keep.txt"]);
463
    assert!(!root.join("x.txt").exists());
464
}
465
466
/// Removing, renaming, or committing just the path of a unified file
467
/// retires its duplicate with it, so the conflict never comes back.
468
#[test]
469
fn unified_additions_stay_one_when_removed_renamed_or_committed_alone() {
470
    hermetic();
471
    let add = |root: &Path, _: bool| write(root, "x.txt", b"same\n");
472
    for how in ["remove", "rename", "path", "hunk"] {
473
        let (dir, repo, _, _) = merged_additions(add);
474
        let root = dir.path();
475
        match how {
476
            "remove" => fs::remove_file(root.join("x.txt")).unwrap(),
477
            "rename" => fs::rename(root.join("x.txt"), root.join("y.txt")).unwrap(),
478
            _ => {
479
                write(root, "x.txt", b"same\nmore\n");
480
                write(root, "other.txt", b"o\n");
481
            }
482
        }
483
        let s = repo.snapshot("status").unwrap();
484
        let h = match how {
485
            "path" => repo
486
                .commit_selection("x alone", &[], &Selection::Paths(vec!["x.txt".into()]))
487
                .unwrap(),
488
            "hunk" => {
489
                let (_, hunks) = repo.hunks().unwrap();
490
                // The duplicate's retirement is no hunk of its own.
491
                assert!(hunks.iter().all(|h| !h.text.starts_with("D ")), "{hunks:?}");
492
                let x: Vec<usize> = hunks
493
                    .iter()
494
                    .filter(|h| h.path == "x.txt")
495
                    .map(|h| h.index)
496
                    .collect();
497
                assert!(!x.is_empty());
498
                repo.commit_selection("x hunks", &[], &Selection::Hunks(x))
499
                    .unwrap()
500
            }
501
            _ => repo.commit(how, &[]).unwrap(),
502
        };
503
        assert!(!s.base_snapshot.is_conflicted());
504
        let heads = repo.bookmark_heads().unwrap();
505
        assert!(heads.contains(&h));
506
        let snap = repo.load_state(&heads).unwrap().materialize();
507
        assert!(!snap.is_conflicted(), "{how}: {:?}", snap.tree.conflicts);
508
        let want: &[&str] = match how {
509
            "remove" => &["keep.txt"],
510
            "rename" => &["keep.txt", "y.txt"],
511
            _ => &["keep.txt", "x.txt"],
512
        };
513
        assert_eq!(
514
            snap.files.keys().cloned().collect::<Vec<_>>(),
515
            want,
516
            "{how}"
517
        );
518
        assert!(conflict_copies(root).is_empty(), "{how}");
519
    }
520
}
521
522
/// The same path added with different content, or a different mode, is a
523
/// name conflict as before.
524
#[test]
525
fn additions_that_differ_still_conflict() {
526
    hermetic();
527
    #[cfg(unix)]
528
    use std::os::unix::fs::PermissionsExt;
529
    let content =
530
        |root: &Path, side: bool| write(root, "x.txt", if side { b"two\n" } else { b"one\n" });
531
    let mode = |root: &Path, side: bool| {
532
        write(root, "x.txt", b"same\n");
533
        #[cfg(unix)]
534
        if side {
535
            fs::set_permissions(root.join("x.txt"), fs::Permissions::from_mode(0o755)).unwrap();
536
        }
537
    };
538
    let check = |what: &str, side: &dyn Fn(&Path, bool)| {
539
        let (dir, repo, heads, _) = merged_additions(side);
540
        let snap = repo.load_state(&heads).unwrap().materialize();
541
        assert!(snap.tree.unified.is_empty(), "{what}");
542
        assert!(
543
            snap.tree.conflicts.iter().any(
544
                |c| matches!(c, crate::tree::TreeConflict::Name { name, .. } if name == "x.txt")
545
            ),
546
            "{what}: {:?}",
547
            snap.tree.conflicts
548
        );
549
        assert_eq!(
550
            conflict_copies(dir.path()),
551
            ["x.txt.oxy-conflict-1", "x.txt.oxy-conflict-2"],
552
            "{what}"
553
        );
554
        assert!(!dir.path().join("x.txt").exists(), "{what}");
555
    };
556
    check("content", &content);
557
    #[cfg(unix)]
558
    check("mode", &mode);
559
    #[cfg(not(unix))]
560
    let _ = mode;
561
}
562
563
/// The same subrepo at the same pin, added on two bookmarks, is one
564
/// subrepo after the merge (oxygen#101), as is the identical
565
/// `.oxymodules` beside it.
566
#[test]
567
fn the_same_subrepo_added_on_two_bookmarks_unifies() {
568
    hermetic();
569
    let dir = tempfile::tempdir().unwrap();
570
    let root = dir.path();
571
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
572
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
573
    let lib = Repo::clone(&lib_url, &root.join("lib"))
574
        .unwrap()
575
        .with_home(root.join("home"));
576
    write(&root.join("lib"), "lib.txt", b"v1\n");
577
    lib.commit("lib v1", &[]).unwrap();
578
    assert!(lib.push("origin", false).unwrap()[0].ok);
579
    let _ = lib_origin;
580
581
    let app_dir = root.join("app");
582
    let mut app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
583
    write(&app_dir, "main.txt", b"app\n");
584
    app.commit("base", &[]).unwrap();
585
    app.bookmark_create("side", None).unwrap();
586
    app.submodule_add(&lib_url, "rstar-api", None).unwrap();
587
    let modules = fs::read(app_dir.join(".oxymodules")).unwrap();
588
    app.commit("rstar-api on main", &[]).unwrap();
589
    // On the other bookmark the nested repository is still there (it is
590
    // never deleted); registering it again adds it at the same pin.
591
    app.bookmark_switch("side", false).unwrap();
592
    assert!(app_dir.join("rstar-api/.oxy").is_dir());
593
    write(&app_dir, ".oxymodules", &modules);
594
    let s = app.snapshot("status").unwrap();
595
    assert_eq!(
596
        statuses(&s),
597
        vec![
598
            (".oxymodules".into(), ChangeStatus::Added),
599
            ("rstar-api".into(), ChangeStatus::Added)
600
        ]
601
    );
602
    app.commit("rstar-api on side", &[]).unwrap();
603
    app.bookmark_switch("main", false).unwrap();
604
605
    let m = app.merge("side").unwrap();
606
    assert!(m.changed && m.checked_out);
607
    let snap = app.load_state(&m.heads).unwrap().materialize();
608
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
609
    assert_eq!(snap.tree.unified.len(), 2);
610
    assert_eq!(snap.files["rstar-api"].kind, NodeKind::Subrepo);
611
    assert!(conflict_copies(&app_dir).is_empty());
612
    let s = app.snapshot("status").unwrap();
613
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
614
    assert!(!s.base_snapshot.is_conflicted());
615
    assert_eq!(
616
        fs::read_to_string(app_dir.join("rstar-api/lib.txt")).unwrap(),
617
        "v1\n"
618
    );
619
}
620
621
#[test]
622
fn identities_and_signed_commits() {
623
    hermetic();
624
    let dir = tempfile::tempdir().unwrap();
625
    let root = dir.path();
626
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
627
    write(root, "a.txt", b"a\n");
628
    let h0 = repo.commit("unsigned", &[]).unwrap();
629
    assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
630
    assert_eq!(
631
        repo.store().get_change(&h0).unwrap().author,
632
        ObjectRef::ZERO
633
    );
634
635
    let (key, id) = repo
636
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
637
        .unwrap();
638
    assert_eq!(id.hash(), key);
639
    assert_eq!(repo.config.author_key, Some(key));
640
    // Config survives reopen; the secret key is found again.
641
    let reopened = Repo::open(root).unwrap().with_home(root.join("home"));
642
    assert_eq!(reopened.config.author_key, Some(key));
643
    assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
644
645
    // Default core.sign = seal: commits carry the author but no signature.
646
    write(root, "a.txt", b"a\nb\n");
647
    let h1 = repo.commit("authored", &[]).unwrap();
648
    assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
649
    assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
650
    // Signing later works too.
651
    repo.sign_change(&h1).unwrap();
652
    assert!(
653
        matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
654
    );
655
656
    repo.config.set("core.sign", "change").unwrap();
657
    repo.save_config().unwrap();
658
    write(root, "a.txt", b"a\nb\nc\n");
659
    let h2 = repo.commit("signed", &[]).unwrap();
660
    assert_eq!(
661
        repo.verify_change(&h2).unwrap(),
662
        SignatureStatus::Valid {
663
            key,
664
            name: "Ada".into(),
665
            email: "[email protected]".into(),
666
            sealed: false,
667
            revoked: false
668
        }
669
    );
670
671
    // A signature by a key that is not the author or a delegate is rejected
672
    // when the change names an author; an anonymous change (made before any
673
    // identity, author zero) is adopted by whoever signs it (spec §14.4).
674
    let other = SecretKey::generate();
675
    let other_id = other.identity("Mallory", "[email protected]", 0);
676
    let other_key = repo.store().put_identity(&other_id).unwrap();
677
    write(root, "a.txt", b"a\nb\nc\nd\n");
678
    repo.config.set("core.sign", "seal").unwrap();
679
    let h3 = repo.commit("ada's, unsigned", &[]).unwrap();
680
    let forged = other.sign(Domain::Change, &other_key, &h3);
681
    repo.store().put_signature(&h3, &forged).unwrap();
682
    assert!(
683
        matches!(repo.verify_change(&h3).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author"))
684
    );
685
    let adopted = other.sign(Domain::Change, &other_key, &h0);
686
    repo.store().put_signature(&h0, &adopted).unwrap();
687
    assert!(
688
        matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Valid { name, .. } if name == "Mallory")
689
    );
690
691
    // Tampering with the stored signature invalidates it.
692
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
693
    sig.ed[0] ^= 1;
694
    repo.store().put_signature(&h2, &sig).unwrap();
695
    assert!(matches!(
696
        repo.verify_change(&h2).unwrap(),
697
        SignatureStatus::Invalid(_)
698
    ));
699
700
    // Without the secret key, signing at commit fails cleanly.
701
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
702
    write(root, "a.txt", b"z\n");
703
    assert!(no_keys.commit("cannot sign", &[]).is_err());
704
}
705
706
#[test]
707
fn checkout_moves_the_working_copy() {
708
    hermetic();
709
    let dir = tempfile::tempdir().unwrap();
710
    let root = dir.path();
711
    let repo = Repo::init(root).unwrap();
712
    write(root, "a.txt", b"one\n");
713
    write(root, "sub/deep/b.txt", b"b\n");
714
    let h1 = repo.commit("first", &[]).unwrap();
715
    write(root, "a.txt", b"two\n");
716
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
717
    write(root, "bin.dat", &[0, 1, 2, 3]);
718
    let h2 = repo.commit("second", &[]).unwrap();
719
720
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
721
    assert_eq!(
722
        r,
723
        CheckoutReport {
724
            written: 2,
725
            removed: 1,
726
            conflicted: false,
727
            notes: vec![],
728
            lacks: 1,
729
        }
730
    );
731
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
732
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
733
    assert!(!root.join("bin.dat").exists());
734
    let (_, wc) = repo.working_copy().unwrap();
735
    assert_eq!(wc.deps, vec![h1]);
736
    assert!(
737
        !repo.snapshot("status").unwrap().changed,
738
        "checkout leaves a clean working copy"
739
    );
740
    // The bookmark still points at h2.
741
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
742
743
    // Dirty working copy refuses without --discard.
744
    write(root, "a.txt", b"dirty\n");
745
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
746
    let r = repo
747
        .checkout(&[h2], true, "oxy checkout --discard")
748
        .unwrap();
749
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
750
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
751
    assert!(!root.join("sub").exists(), "empty directories are pruned");
752
    assert_eq!(r.removed, 1);
753
    assert!(!repo.snapshot("status").unwrap().changed);
754
755
    // Refuses to write through a symlinked directory.
756
    #[cfg(unix)]
757
    {
758
        fs::remove_dir_all(root.join("sub")).ok();
759
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
760
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
761
    }
762
}
763
764
#[test]
765
fn large_files_are_chunked_and_read_back() {
766
    hermetic();
767
    let dir = tempfile::tempdir().unwrap();
768
    let repo = Repo::init(dir.path()).unwrap();
769
    let mut big = vec![0u8; 700 * 1024];
770
    for (i, b) in big.iter_mut().enumerate() {
771
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
772
    }
773
    let r = repo.store_blob(&big).unwrap();
774
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
775
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
776
    assert_eq!(repo.read_blob(&r).unwrap(), big);
777
    assert_eq!(Repo::blob_ref(&big), r);
778
}
779
780
#[test]
781
fn clone_push_pull_with_seals_and_attestations() {
782
    hermetic();
783
    let dir = tempfile::tempdir().unwrap();
784
    let root = dir.path();
785
    let origin_path = root.join("origin");
786
    let origin = Repo::init(&origin_path).unwrap();
787
    let origin_url = origin_path.to_string_lossy().to_string();
788
789
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
790
    let mut a = Repo::clone(&origin_url, &root.join("a"))
791
        .unwrap()
792
        .with_home(root.join("home-a"));
793
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
794
    let (key_a, _) = a
795
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
796
        .unwrap();
797
    write(&root.join("a"), "f.txt", b"a\n");
798
    let h1 = a.commit("first", &[]).unwrap();
799
    let results = a.push("origin", false).unwrap();
800
    assert!(results[0].ok, "{}", results[0].reason);
801
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
802
    // The change was sealed at push and the reference attested.
803
    assert!(
804
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
805
    );
806
    assert_eq!(
807
        origin.verify_change(&h1).unwrap(),
808
        SignatureStatus::Unsigned
809
    );
810
    let serial_of = |att: &SignedAttest| match att.attest.body {
811
        AttestBody::Ref { serial, .. } => serial,
812
        _ => unreachable!(),
813
    };
814
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
815
    // A bookmark new to the remote starts at the clock (past any deleted
816
    // namesake's serial); later updates count up from there.
817
    let first = serial_of(&att);
818
    assert!(first > 1_000_000_000_000, "{first}");
819
    let again = a.push("origin", false).unwrap();
820
    assert!(again[0].ok && again[0].reason.contains("up to date"));
821
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
822
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
823
824
    // B clones and sees the file and the seal.
825
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
826
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
827
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
828
    assert!(matches!(
829
        b.authenticate_change(&h1).unwrap(),
830
        SignatureStatus::Valid { sealed: true, .. }
831
    ));
832
833
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
834
    write(&root.join("b"), "f.txt", b"a\nb\n");
835
    let h2 = b.commit("second", &[]).unwrap();
836
    assert!(b.push("origin", false).unwrap()[0].ok);
837
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
838
839
    // A commits an independent change; push is refused until A pulls.
840
    write(&root.join("a"), "g.txt", b"g\n");
841
    let h3 = a.commit("third", &[]).unwrap();
842
    assert!(a.push("origin", false).is_err());
843
    let pr = a.pull("origin").unwrap();
844
    assert!(pr.changed && pr.checked_out);
845
    let mut want = vec![h2, h3];
846
    want.sort();
847
    assert_eq!(pr.heads, want);
848
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
849
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
850
    let results = a.push("origin", false).unwrap();
851
    assert!(results[0].ok, "{}", results[0].reason);
852
    let mut origin_heads = origin.bookmark_heads().unwrap();
853
    origin_heads.sort();
854
    assert_eq!(origin_heads, want);
855
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
856
    assert_eq!(serial_of(&att), first + 1);
857
858
    // B pulls and ends up identical.
859
    let pr = b.pull("origin").unwrap();
860
    assert_eq!(pr.heads, want);
861
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
862
    assert!(!b.snapshot("status").unwrap().changed);
863
864
    // Concurrent edits of the same line: the union is a reified conflict.
865
    write(&root.join("a"), "f.txt", b"a\nA\n");
866
    a.commit("a-edit", &[]).unwrap();
867
    a.push("origin", false).unwrap();
868
    write(&root.join("b"), "f.txt", b"a\nB\n");
869
    b.commit("b-edit", &[]).unwrap();
870
    let pr = b.pull("origin").unwrap();
871
    assert!(pr.changed && pr.checked_out);
872
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
873
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
874
    write(&root.join("b"), "f.txt", b"a\nAB\n");
875
    let hr = b.commit("resolve", &[]).unwrap();
876
    assert_eq!(
877
        b.store().get_change(&hr).unwrap().kind,
878
        ChangeKind::Resolution
879
    );
880
    assert!(b.push("origin", false).unwrap()[0].ok);
881
    a.pull("origin").unwrap();
882
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
883
    // The resolution depends on the conflicting edits, but nothing depends
884
    // on "third" (it only added g.txt), so it stays a head beside it.
885
    let mut want = vec![hr, h3];
886
    want.sort();
887
    assert_eq!(a.bookmark_heads().unwrap(), want);
888
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
889
}
890
891
#[test]
892
fn receive_push_rejects_bad_updates() {
893
    hermetic();
894
    let dir = tempfile::tempdir().unwrap();
895
    let root = dir.path();
896
    let origin = Repo::init(&root.join("origin")).unwrap();
897
    let url = root.join("origin").to_string_lossy().to_string();
898
    let mut a = Repo::clone(&url, &root.join("a"))
899
        .unwrap()
900
        .with_home(root.join("home"));
901
    let (key, _) = a
902
        .create_identity("Ada", "a@b", IdentityScope::Repo)
903
        .unwrap();
904
    write(&root.join("a"), "f.txt", b"x\n");
905
    let h1 = a.commit("one", &[]).unwrap();
906
    assert!(a.push("origin", false).unwrap()[0].ok);
907
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
908
    let s1 = origin
909
        .store()
910
        .put_state(&StateObject::new(vec![h1]))
911
        .unwrap();
912
913
    // Missing head.
914
    let ghost = origin
915
        .store()
916
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
917
        .unwrap();
918
    let r = origin
919
        .receive_push(
920
            Bundle::default(),
921
            vec![RefUpdate {
922
                name: "main".into(),
923
                old_state: s1,
924
                new_state: ghost,
925
                force: false,
926
                attestation: None,
927
            }],
928
            None,
929
            vec![],
930
        )
931
        .unwrap();
932
    assert!(
933
        !r[0].ok && r[0].reason.contains("missing"),
934
        "{}",
935
        r[0].reason
936
    );
937
938
    // Stale old_state.
939
    let r = origin
940
        .receive_push(
941
            Bundle::default(),
942
            vec![RefUpdate {
943
                name: "main".into(),
944
                old_state: empty,
945
                new_state: s1,
946
                force: false,
947
                attestation: None,
948
            }],
949
            None,
950
            vec![],
951
        )
952
        .unwrap();
953
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
954
955
    // Non-fast-forward without force is refused; with force it passes.
956
    let r = origin
957
        .receive_push(
958
            Bundle::default(),
959
            vec![RefUpdate {
960
                name: "main".into(),
961
                old_state: s1,
962
                new_state: empty,
963
                force: false,
964
                attestation: None,
965
            }],
966
            None,
967
            vec![],
968
        )
969
        .unwrap();
970
    assert!(
971
        !r[0].ok && r[0].reason.contains("fast-forward"),
972
        "{}",
973
        r[0].reason
974
    );
975
    let r = origin
976
        .receive_push(
977
            Bundle::default(),
978
            vec![RefUpdate {
979
                name: "main".into(),
980
                old_state: s1,
981
                new_state: empty,
982
                force: true,
983
                attestation: None,
984
            }],
985
            None,
986
            vec![],
987
        )
988
        .unwrap();
989
    assert!(r[0].ok);
990
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
991
992
    // Attestation with a stale serial is a rollback and is refused.
993
    let sa = a
994
        .sign_attest(&Attest {
995
            repo: a.id().unwrap(),
996
            hlc: Hlc::now(),
997
            body: AttestBody::Ref {
998
                name: "main".into(),
999
                old_state: empty,
1000
                new_state: s1,
1001
                serial: 1,
1002
            },
1003
        })
1004
        .unwrap();
1005
    let r = origin
1006
        .receive_push(
1007
            Bundle::default(),
1008
            vec![RefUpdate {
1009
                name: "main".into(),
1010
                old_state: empty,
1011
                new_state: s1,
1012
                force: false,
1013
                attestation: Some(sa.clone()),
1014
            }],
1015
            None,
1016
            vec![],
1017
        )
1018
        .unwrap();
1019
    assert!(
1020
        !r[0].ok && r[0].reason.contains("serial"),
1021
        "{}",
1022
        r[0].reason
1023
    );
1024
    // An attestation for a different update is refused too.
1025
    let sa2 = a
1026
        .sign_attest(&Attest {
1027
            repo: a.id().unwrap(),
1028
            hlc: Hlc::now(),
1029
            body: AttestBody::Ref {
1030
                name: "main".into(),
1031
                old_state: s1,
1032
                new_state: empty,
1033
                serial: 5,
1034
            },
1035
        })
1036
        .unwrap();
1037
    let r = origin
1038
        .receive_push(
1039
            Bundle::default(),
1040
            vec![RefUpdate {
1041
                name: "main".into(),
1042
                old_state: empty,
1043
                new_state: s1,
1044
                force: false,
1045
                attestation: Some(sa2),
1046
            }],
1047
            None,
1048
            vec![],
1049
        )
1050
        .unwrap();
1051
    assert!(
1052
        !r[0].ok && r[0].reason.contains("describe"),
1053
        "{}",
1054
        r[0].reason
1055
    );
1056
    let _ = key;
1057
}
1058
1059
#[test]
1060
fn user_config_supplies_defaults_and_clones_sign() {
1061
    hermetic();
1062
    let dir = tempfile::tempdir().unwrap();
1063
    let root = dir.path();
1064
    let home = root.join("home");
1065
    let origin = Repo::init(&root.join("origin")).unwrap();
1066
    let url = root.join("origin").to_string_lossy().to_string();
1067
1068
    // Identity at user scope: the repository file stays free of author keys.
1069
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
1070
    let (key, _) = a
1071
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1072
        .unwrap();
1073
    assert!(!a.config.repo_layer().contains_key("author.key"));
1074
    assert_eq!(a.config.author_key, Some(key));
1075
    assert!(home.join("config.toml").exists());
1076
    a.set_user_config("core.sign", "change").unwrap();
1077
    assert!(a.config.sign_changes);
1078
1079
    // Repository settings override user settings and are the only ones saved.
1080
    a.config.set("core.sign", "seal").unwrap();
1081
    a.save_config().unwrap();
1082
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
1083
    assert!(!again.config.sign_changes);
1084
    assert_eq!(again.config.author_key, Some(key));
1085
    assert_eq!(
1086
        read_config_file(&root.join("a/.oxy/config"))
1087
            .unwrap()
1088
            .get("core.sign")
1089
            .map(String::as_str),
1090
        Some("seal")
1091
    );
1092
1093
    // A fresh clone made by this user signs with the user-level identity,
1094
    // even though the clone's store has never seen the identity object.
1095
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
1096
    assert!(b.config.sign_changes);
1097
    write(&root.join("b"), "f.txt", b"f\n");
1098
    let h = b.commit("signed from a clone", &[]).unwrap();
1099
    assert!(
1100
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
1101
    );
1102
    assert!(b.push("origin", false).unwrap()[0].ok);
1103
    assert!(matches!(
1104
        origin.verify_change(&h).unwrap(),
1105
        SignatureStatus::Valid { .. }
1106
    ));
1107
}
1108
1109
#[test]
1110
fn format1_repositories_are_migrated_on_open() {
1111
    hermetic();
1112
    use crate::oplog::{Format1Op, Format1View};
1113
    let dir = tempfile::tempdir().unwrap();
1114
    let root = dir.path();
1115
    let repo = Repo::init(root).unwrap();
1116
    write(root, "a.txt", b"a\n");
1117
    let h1 = repo.commit("one", &[]).unwrap();
1118
    let (wc_hash, _) = repo.working_copy().unwrap();
1119
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
1120
    let mut v1 = Format1View::default();
1121
    v1.bookmarks.insert("main".into(), vec![]);
1122
    v1.workspaces.insert(repo.workspace(), wc_hash);
1123
    let init = Format1Op {
1124
        parents: vec![],
1125
        hlc: Hlc::default(),
1126
        command: "oxy init".into(),
1127
        view: v1.clone(),
1128
    };
1129
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
1130
    v1.bookmarks.insert("main".into(), vec![h1]);
1131
    let commit = Format1Op {
1132
        parents: vec![init_ref],
1133
        hlc: Hlc::default(),
1134
        command: "oxy commit".into(),
1135
        view: v1,
1136
    };
1137
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
1138
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
1139
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
1140
    drop(repo);
1141
1142
    let repo = Repo::open(root).unwrap();
1143
    assert_eq!(
1144
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
1145
        FORMAT_LINE
1146
    );
1147
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
1148
    let ops = repo.op_log().unwrap();
1149
    assert_eq!(
1150
        ops.iter()
1151
            .map(|(_, o)| o.command.as_str())
1152
            .collect::<Vec<_>>(),
1153
        ["oxy commit", "oxy init"]
1154
    );
1155
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
1156
    assert!(!repo.snapshot("status").unwrap().changed);
1157
    // Reopening again is a no-op.
1158
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
1159
}
1160
1161
#[test]
1162
fn undo_skips_snapshot_operations() {
1163
    hermetic();
1164
    let dir = tempfile::tempdir().unwrap();
1165
    let root = dir.path();
1166
    let repo = Repo::init(root).unwrap();
1167
    write(root, "a.txt", b"a\n");
1168
    let h1 = repo.commit("a", &[]).unwrap();
1169
    // A later command snapshots new edits on top of the commit.
1170
    write(root, "b.txt", b"b\n");
1171
    let s = repo.snapshot("oxy status").unwrap();
1172
    assert!(s.changed);
1173
    assert!(repo.head_op().unwrap().1.is_snapshot());
1174
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
1175
    // Undo must undo the commit, not the snapshot.
1176
    repo.undo().unwrap();
1177
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
1178
    let s = repo.snapshot("oxy status").unwrap();
1179
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
1180
    assert_eq!(
1181
        paths,
1182
        ["a.txt", "b.txt"],
1183
        "both files are back in the working copy"
1184
    );
1185
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
1186
    // Only snapshots remain above `init`, so there is nothing left to undo.
1187
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
1188
    assert!(repo.undo().is_err());
1189
}
1190
1191
#[test]
1192
fn independent_changes_commute_and_make_multiple_heads() {
1193
    hermetic();
1194
    let dir = tempfile::tempdir().unwrap();
1195
    let root = dir.path();
1196
    let repo = Repo::init(root).unwrap();
1197
    write(root, "a.txt", b"a\n");
1198
    let h1 = repo.commit("a", &[]).unwrap();
1199
    write(root, "b.txt", b"b\n");
1200
    let h2 = repo.commit("b", &[]).unwrap();
1201
    let c2 = repo.store().get_change(&h2).unwrap();
1202
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
1203
    let mut heads = repo.bookmark_heads().unwrap();
1204
    heads.sort();
1205
    let mut want = vec![h1, h2];
1206
    want.sort();
1207
    assert_eq!(heads, want);
1208
    // Editing a.txt depends on h1 only.
1209
    write(root, "a.txt", b"a\na2\n");
1210
    let h3 = repo.commit("a2", &[]).unwrap();
1211
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
1212
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1213
    assert_eq!(heads, [h2, h3].into_iter().collect());
1214
    // Explicit dependency.
1215
    write(root, "c.txt", b"c\n");
1216
    let h4 = repo.commit("c", &[h2]).unwrap();
1217
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
1218
}
1219
1220
#[test]
1221
fn mode_change_and_text_binary_switch() {
1222
    hermetic();
1223
    let dir = tempfile::tempdir().unwrap();
1224
    let root = dir.path();
1225
    let repo = Repo::init(root).unwrap();
1226
    write(root, "run.sh", b"#!/bin/sh\n");
1227
    repo.commit("add script", &[]).unwrap();
1228
    #[cfg(unix)]
1229
    {
1230
        use std::os::unix::fs::PermissionsExt;
1231
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1232
        let s = repo.snapshot("status").unwrap();
1233
        assert_eq!(
1234
            statuses(&s),
1235
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
1236
        );
1237
        let h = repo.commit("exec", &[]).unwrap();
1238
        let snap = repo.load_state(&[h]).unwrap().materialize();
1239
        assert!(snap.files["run.sh"].mode.exec);
1240
    }
1241
    // Text → binary → text.
1242
    write(root, "run.sh", b"\0binary");
1243
    let h = repo.commit("binary", &[]).unwrap();
1244
    let snap = repo.load_state(&[h]).unwrap().materialize();
1245
    assert!(snap.files["run.sh"].mode.opaque);
1246
    write(root, "run.sh", b"text again\n");
1247
    let h = repo.commit("text", &[]).unwrap();
1248
    let snap = repo.load_state(&[h]).unwrap().materialize();
1249
    assert!(!snap.files["run.sh"].mode.opaque);
1250
    assert!(
1251
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
1252
    );
1253
    assert!(!snap.is_conflicted());
1254
}
1255
1256
#[test]
1257
fn trust_policy_governs_pushes_and_fetches() {
1258
    hermetic();
1259
    let dir = tempfile::tempdir().unwrap();
1260
    let root = dir.path();
1261
    let origin = Repo::init(&root.join("origin")).unwrap();
1262
    let url = root.join("origin").to_string_lossy().to_string();
1263
1264
    // A is the root. Before the policy, an unsigned push from B is fine.
1265
    let mut a = Repo::clone(&url, &root.join("a"))
1266
        .unwrap()
1267
        .with_home(root.join("home-a"));
1268
    let (key_a, _) = a
1269
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1270
        .unwrap();
1271
    let mut b = Repo::clone(&url, &root.join("b"))
1272
        .unwrap()
1273
        .with_home(root.join("home-b"));
1274
    write(&root.join("b"), "b.txt", b"b\n");
1275
    b.commit("unsigned before policy", &[]).unwrap();
1276
    assert!(b.push("origin", false).unwrap()[0].ok);
1277
1278
    // A creates the policy and pushes it; origin now enforces it.
1279
    write(&root.join("a"), "a.txt", b"a\n");
1280
    a.commit("a", &[]).unwrap();
1281
    let sp = a.policy_init().unwrap();
1282
    assert_eq!(sp.policy.serial, 1);
1283
    a.pull("origin").unwrap();
1284
    let results = a.push("origin", false).unwrap();
1285
    assert!(results.iter().all(|r| r.ok), "{results:?}");
1286
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
1287
1288
    // B pulls the policy. Without an identity B cannot push at all.
1289
    b.pull("origin").unwrap();
1290
    assert!(
1291
        b.current_policy().unwrap().is_some(),
1292
        "the policy arrived with the fetch"
1293
    );
1294
    assert!(b.push("origin", false).is_err());
1295
    // With an identity the policy does not list, the push is rejected by origin.
1296
    let (key_b, id_b) = b
1297
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1298
        .unwrap();
1299
    write(&root.join("b"), "b.txt", b"b2\n");
1300
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1301
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1302
    let r = b.push("origin", false).unwrap();
1303
    assert!(
1304
        !r[0].ok && r[0].reason.contains("may not update"),
1305
        "{:?}",
1306
        r
1307
    );
1308
1309
    // A grants B (identity handed over as a file) and publishes the policy.
1310
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1311
    assert_eq!(sp.policy.serial, 2);
1312
    let r = a.push("origin", false).unwrap();
1313
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1314
    // B must fetch the new policy before pushing.
1315
    assert!(b
1316
        .push("origin", false)
1317
        .unwrap_or_else(|e| vec![RefResult {
1318
            name: "main".into(),
1319
            ok: false,
1320
            reason: e.to_string()
1321
        }])
1322
        .iter()
1323
        .all(|x| !x.ok));
1324
    b.pull("origin").unwrap();
1325
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1326
    let r = b.push("origin", false).unwrap();
1327
    assert!(r[0].ok, "{:?}", r);
1328
    // Origin verified B's change under the policy.
1329
    let heads = origin.bookmark_heads().unwrap();
1330
    for h in &heads {
1331
        let c = origin.store().get_change(h).unwrap();
1332
        if c.author == key_b {
1333
            origin
1334
                .change_allowed(
1335
                    h,
1336
                    &origin.current_policy().unwrap().unwrap().1.policy,
1337
                    "main",
1338
                )
1339
                .unwrap();
1340
        }
1341
    }
1342
1343
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1344
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1345
    forged.serial = 3;
1346
    forged.roots = vec![key_b];
1347
    let fh = forged.hash();
1348
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
1349
    let forged = SignedPolicy {
1350
        policy: forged,
1351
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1352
    };
1353
    let r = origin
1354
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1355
        .unwrap();
1356
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1357
    let stale = a.current_policy().unwrap().unwrap().1;
1358
    let mut old = stale.clone();
1359
    old.policy.serial = 1;
1360
    let r = origin
1361
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1362
        .unwrap();
1363
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1364
1365
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1366
    a.pull("origin").unwrap();
1367
    a.policy_revoke(&key_b).unwrap();
1368
    let r = a.push("origin", false).unwrap();
1369
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1370
    b.pull("origin").unwrap();
1371
    write(&root.join("b"), "b.txt", b"b3\n");
1372
    b.commit("b3", &[]).unwrap();
1373
    let r = b.push("origin", false).unwrap();
1374
    assert!(!r[0].ok, "{:?}", r);
1375
1376
    // A clone by a third party receives and verifies everything.
1377
    let c = Repo::clone(&url, &root.join("c"))
1378
        .unwrap()
1379
        .with_home(root.join("home-c"));
1380
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
1381
    assert!(c
1382
        .current_policy()
1383
        .unwrap()
1384
        .unwrap()
1385
        .1
1386
        .policy
1387
        .roots
1388
        .contains(&key_a));
1389
    assert!(!c.snapshot("status").unwrap().changed);
1390
}
1391
1392
/// oxygen#66: a gc says what it is doing, phase by phase.
1393
#[test]
1394
fn gc_reports_its_phases() {
1395
    hermetic();
1396
    let dir = tempfile::tempdir().unwrap();
1397
    let repo = Repo::init(dir.path()).unwrap();
1398
    for i in 0..3 {
1399
        write(
1400
            dir.path(),
1401
            &format!("f{i}.txt"),
1402
            format!("{i}\n").as_bytes(),
1403
        );
1404
        repo.commit(&format!("c{i}"), &[]).unwrap();
1405
    }
1406
    let mut phases = Vec::new();
1407
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
1408
        .unwrap();
1409
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
1410
    assert!(
1411
        phases.iter().any(|p| p.starts_with("pruning")),
1412
        "{phases:?}"
1413
    );
1414
    assert!(
1415
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
1416
        "{phases:?}"
1417
    );
1418
    assert!(
1419
        phases
1420
            .iter()
1421
            .any(|p| p.starts_with("writing the index of ")),
1422
        "{phases:?}"
1423
    );
1424
}
1425
1426
#[test]
1427
fn gc_packs_objects_and_history_still_works() {
1428
    hermetic();
1429
    let dir = tempfile::tempdir().unwrap();
1430
    let root = dir.path();
1431
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1432
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1433
        .unwrap();
1434
    repo.set_user_config("core.sign", "change").unwrap();
1435
    write(root, "a.txt", b"one\n");
1436
    let h1 = repo.commit("one", &[]).unwrap();
1437
    write(root, "a.txt", b"two\n");
1438
    write(root, "big.bin", &vec![0u8; 100_000]);
1439
    let h2 = repo.commit("two", &[]).unwrap();
1440
    // Several snapshots leave superseded working-copy versions behind.
1441
    for i in 0..5 {
1442
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1443
        repo.snapshot("status").unwrap();
1444
    }
1445
    write(root, "a.txt", b"two\n");
1446
    repo.snapshot("status").unwrap();
1447
    let before = repo.store().list().unwrap();
1448
    assert!(repo.store().loose_count().unwrap() > 0);
1449
1450
    // With the default retention every operation's view is a root: nothing prunes.
1451
    let r = repo.gc(true).unwrap();
1452
    assert_eq!(r.packed.objects, before.len());
1453
    assert_eq!(r.pruned.objects, 0);
1454
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1455
    assert_eq!(repo.store().list().unwrap(), before);
1456
1457
    // With zero retention only the current view is a root: superseded
1458
    // working copies go, everything reachable stays.
1459
    repo.config.set("core.op-retention", "0").unwrap();
1460
    repo.save_config().unwrap();
1461
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
1462
    let r = repo.gc(true).unwrap();
1463
    assert!(r.pruned.objects >= 5, "{r:?}");
1464
    let after = repo.store().list().unwrap();
1465
    assert!(after.len() < before.len());
1466
    assert!(after.contains(&h1) && after.contains(&h2));
1467
    for (_, op) in repo.op_log().unwrap() {
1468
        assert!(!op.command.is_empty(), "operation objects are all kept");
1469
    }
1470
    // Everything still works from the pruned, packed store.
1471
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
1472
    assert!(matches!(
1473
        repo.verify_change(&h2).unwrap(),
1474
        SignatureStatus::Valid { .. }
1475
    ));
1476
    assert_eq!(repo.log().unwrap().len(), 3);
1477
    repo.checkout(&[h1], false, "checkout").unwrap();
1478
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1479
    repo.checkout(&[h2], false, "checkout").unwrap();
1480
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1481
    assert!(!repo.snapshot("status").unwrap().changed);
1482
    // Grace period defers pruning of young garbage.
1483
    write(root, "a.txt", b"three\n");
1484
    repo.commit("three", &[]).unwrap();
1485
    let r = repo.gc(false).unwrap();
1486
    assert_eq!(r.pruned.objects, 0);
1487
    assert!(r.pruned.deferred > 0);
1488
    let r = repo.gc(true).unwrap();
1489
    assert!(r.pruned.objects > 0);
1490
    assert_eq!(repo.log().unwrap().len(), 4);
1491
    // Restoring the default retention makes the old views roots again; the
1492
    // working copies they name were pruned, which gc tolerates.
1493
    repo.config.set("core.op-retention", "90").unwrap();
1494
    repo.save_config().unwrap();
1495
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1496
    let r = repo.gc(false).unwrap();
1497
    assert_eq!(r.pruned.objects, 0);
1498
    assert_eq!(repo.log().unwrap().len(), 4);
1499
}
1500
1501
#[test]
1502
fn describe_amend_abandon_heads() {
1503
    hermetic();
1504
    let dir = tempfile::tempdir().unwrap();
1505
    let root = dir.path();
1506
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1507
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1508
        .unwrap();
1509
    repo.set_user_config("core.sign", "change").unwrap();
1510
    write(root, "a.txt", b"one\n");
1511
    let h1 = repo.commit("first", &[]).unwrap();
1512
    write(root, "a.txt", b"one\ntwo\n");
1513
    let h2 = repo.commit("secnod", &[]).unwrap();
1514
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1515
1516
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1517
    let h2b = repo.describe(&h2, "second").unwrap();
1518
    assert_ne!(h2b, h2);
1519
    let c = repo.store().get_change(&h2b).unwrap();
1520
    assert_eq!(
1521
        (c.change_id, c.message.as_str(), c.deps.clone()),
1522
        (id2, "second", vec![h1])
1523
    );
1524
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
1525
    assert!(matches!(
1526
        repo.verify_change(&h2b).unwrap(),
1527
        SignatureStatus::Valid { .. }
1528
    ));
1529
    let s = repo.snapshot("status").unwrap();
1530
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
1531
    assert_eq!(
1532
        repo.resolve_change(&id2.short(8)).unwrap(),
1533
        h2b,
1534
        "the old object is no longer reachable from the log"
1535
    );
1536
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1537
    let h1b = repo.describe(&h1, "first, described").unwrap();
1538
    assert_ne!(h1b, h1);
1539
    let heads = repo.bookmark_heads().unwrap();
1540
    assert_eq!(heads.len(), 1);
1541
    let top = repo.store().get_change(&heads[0]).unwrap();
1542
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
1543
    assert!(
1544
        matches!(
1545
            repo.verify_change(&heads[0]).unwrap(),
1546
            SignatureStatus::Valid { .. }
1547
        ),
1548
        "rewritten own change is re-signed"
1549
    );
1550
    let (_, wc) = repo.working_copy().unwrap();
1551
    assert_eq!(
1552
        wc.deps,
1553
        vec![heads[0]],
1554
        "the working copy follows the rewrite"
1555
    );
1556
    assert!(!repo.snapshot("status").unwrap().changed);
1557
    let snap = repo.load_state(&heads).unwrap().materialize();
1558
    assert!(
1559
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
1560
    );
1561
1562
    // amend: fold an edit into the head; the result is one change from h1.
1563
    write(root, "a.txt", b"one\ntwo\nthree\n");
1564
    write(root, "b.txt", b"b\n");
1565
    let h2c = repo.amend(None).unwrap();
1566
    let c = repo.store().get_change(&h2c).unwrap();
1567
    assert_eq!(c.change_id, id2);
1568
    assert_eq!(c.message, "second");
1569
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
1570
    assert_eq!(
1571
        repo.log().unwrap().len(),
1572
        3,
1573
        "working copy, amended head, first"
1574
    );
1575
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
1576
    assert!(
1577
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
1578
    );
1579
    assert!(snap.files.contains_key("b.txt"));
1580
    assert!(!repo.snapshot("status").unwrap().changed);
1581
    assert!(
1582
        repo.amend(None).is_err(),
1583
        "clean working copy and no message"
1584
    );
1585
    let h2d = repo.amend(Some("second, amended")).unwrap();
1586
    assert_eq!(
1587
        repo.store().get_change(&h2d).unwrap().message,
1588
        "second, amended"
1589
    );
1590
1591
    // abandon: the head goes, its content stays as uncommitted work.
1592
    repo.abandon(&h2d).unwrap();
1593
    assert_eq!(
1594
        repo.bookmark_heads().unwrap(),
1595
        vec![h1b],
1596
        "the described first change is the head again"
1597
    );
1598
    let s = repo.snapshot("status").unwrap();
1599
    let paths: Vec<_> = s
1600
        .statuses
1601
        .iter()
1602
        .map(|p| (p.path.as_str(), p.status))
1603
        .collect();
1604
    assert_eq!(
1605
        paths,
1606
        vec![
1607
            ("a.txt", ChangeStatus::Modified),
1608
            ("b.txt", ChangeStatus::Added)
1609
        ]
1610
    );
1611
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
1612
    let h3 = repo.commit("recommitted", &[]).unwrap();
1613
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
1614
    // undo brings the abandoned head back.
1615
    repo.undo().unwrap();
1616
    repo.undo().unwrap();
1617
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
1618
1619
    // Abandoning a non-head whose dependent references its atoms reifies
1620
    // the references (here: a.txt vanishes with it, so the dependent's edit
1621
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
1622
    let base = repo.bookmark_heads().unwrap()[0];
1623
    let base_change = repo.store().get_change(&base).unwrap();
1624
    let h1_now = base_change.deps[0];
1625
    let notes = repo.abandon(&h1_now).unwrap();
1626
    assert!(
1627
        !notes.is_empty(),
1628
        "the dependent's edit of a.txt was reified"
1629
    );
1630
    let heads = repo.bookmark_heads().unwrap();
1631
    let after = repo.load_state(&heads).unwrap().materialize();
1632
    assert!(
1633
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
1634
        "{:?}",
1635
        after.files.keys()
1636
    );
1637
    repo.undo().unwrap();
1638
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
1639
    write(root, "c.txt", b"c\n");
1640
    let hc = repo.commit("c", &[]).unwrap();
1641
    write(root, "d.txt", b"d\n");
1642
    let hd = repo.commit("d", &[hc]).unwrap();
1643
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
1644
    repo.abandon(&hc).unwrap();
1645
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1646
    assert!(!heads.contains(&hc));
1647
    let d_now = heads
1648
        .iter()
1649
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
1650
        .copied()
1651
        .unwrap();
1652
    assert!(
1653
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
1654
        "d inherited c's (empty) dependencies"
1655
    );
1656
    let s = repo.snapshot("status").unwrap();
1657
    assert_eq!(
1658
        s.statuses
1659
            .iter()
1660
            .map(|p| p.path.as_str())
1661
            .collect::<Vec<_>>(),
1662
        vec!["c.txt"],
1663
        "c's content is now uncommitted work"
1664
    );
1665
}
1666
1667
#[test]
1668
fn git_export_mirrors_history() {
1669
    hermetic();
1670
    if std::process::Command::new("git")
1671
        .arg("--version")
1672
        .output()
1673
        .is_err()
1674
    {
1675
        eprintln!("git not installed; skipping");
1676
        return;
1677
    }
1678
    let dir = tempfile::tempdir().unwrap();
1679
    let root = dir.path();
1680
    let mut repo = Repo::init(&root.join("r"))
1681
        .unwrap()
1682
        .with_home(root.join("home"));
1683
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
1684
        .unwrap();
1685
    let r = root.join("r");
1686
    write(&r, "README.md", b"hello\n");
1687
    write(&r, "src/main.rs", b"fn main() {}\n");
1688
    let h1 = repo.commit("first", &[]).unwrap();
1689
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
1690
    write(&r, "logo.png", b"\x89PNG\0\0");
1691
    let h2 = repo.commit("second", &[]).unwrap();
1692
1693
    let git_dir = root.join("mirror.git");
1694
    let rep = repo.git_export(&git_dir).unwrap();
1695
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
1696
    let git = |args: &[&str]| -> String {
1697
        let out = std::process::Command::new("git")
1698
            .arg("-C")
1699
            .arg(&git_dir)
1700
            .args(args)
1701
            .output()
1702
            .unwrap();
1703
        assert!(
1704
            out.status.success(),
1705
            "{}",
1706
            String::from_utf8_lossy(&out.stderr)
1707
        );
1708
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1709
    };
1710
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
1711
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1712
    assert_eq!(git(&["show", "main:README.md"]), "hello");
1713
    let body = git(&["log", "-1", "--format=%B", "main"]);
1714
    assert!(
1715
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
1716
        "{body}"
1717
    );
1718
    assert!(body.contains("Change-Id: "), "{body}");
1719
    assert_eq!(
1720
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
1721
        "Ada Lovelace <[email protected]>"
1722
    );
1723
    assert_eq!(
1724
        git(&["ls-tree", "--name-only", "main"]),
1725
        "README.md\nlogo.png\nsrc"
1726
    );
1727
1728
    // Re-export is incremental.
1729
    let rep = repo.git_export(&git_dir).unwrap();
1730
    assert_eq!((rep.exported, rep.skipped), (0, 2));
1731
1732
    // An independent change makes two heads; the next state is one more
1733
    // commit on the linear branch whose tree is the union.
1734
    repo.checkout(&[h1], false, "checkout").unwrap();
1735
    write(&r, "other.txt", b"o\n");
1736
    let h3 = repo.commit("third", &[]).unwrap();
1737
    let rep = repo.git_export(&git_dir).unwrap();
1738
    assert_eq!((rep.exported, rep.heads), (1, 2));
1739
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
1740
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
1741
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
1742
    assert_eq!(git(&["show", "main:other.txt"]), "o");
1743
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1744
    assert_eq!(
1745
        git(&["ls-tree", "--name-only", "main"]),
1746
        "README.md\nlogo.png\nother.txt\nsrc"
1747
    );
1748
    let body = git(&["log", "-1", "--format=%B", "main"]);
1749
    assert!(
1750
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
1751
        "{body}"
1752
    );
1753
    // A rewrite is a new state whose one new change is the rewritten one.
1754
    repo.describe(&h3, "third, described").unwrap();
1755
    let rep = repo.git_export(&git_dir).unwrap();
1756
    assert_eq!(rep.exported, 1);
1757
    assert_eq!(
1758
        git(&["log", "-1", "--format=%s", "main"]),
1759
        "third, described"
1760
    );
1761
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
1762
    let _ = h2;
1763
}
1764
1765
#[test]
1766
fn git_import_reproduces_trees() {
1767
    git_import_reproduces_trees_with(None);
1768
}
1769
1770
/// The same import with every merge rendered in batches of one file
1771
/// (oxygen#25): what a merge onto a base of thousands of files takes.
1772
#[test]
1773
fn git_import_reproduces_trees_in_batches() {
1774
    git_import_reproduces_trees_with(Some(1));
1775
}
1776
1777
fn git_import_reproduces_trees_with(batch: Option<usize>) {
1778
    crate::repo::git::set_merge_batch_for_tests(batch);
1779
    hermetic();
1780
    if std::process::Command::new("git")
1781
        .arg("--version")
1782
        .output()
1783
        .is_err()
1784
    {
1785
        eprintln!("git not installed; skipping");
1786
        return;
1787
    }
1788
    let dir = tempfile::tempdir().unwrap();
1789
    let root = dir.path();
1790
    let g = root.join("src.git");
1791
    fs::create_dir_all(&g).unwrap();
1792
    let git = |args: &[&str]| -> String {
1793
        let out = std::process::Command::new("git")
1794
            .arg("-C")
1795
            .arg(&g)
1796
            .args([
1797
                "-c",
1798
                "user.name=Grace",
1799
                "-c",
1800
                "[email protected]",
1801
                "-c",
1802
                "commit.gpgsign=false",
1803
            ])
1804
            .args(args)
1805
            .output()
1806
            .unwrap();
1807
        assert!(
1808
            out.status.success(),
1809
            "git {args:?}: {}",
1810
            String::from_utf8_lossy(&out.stderr)
1811
        );
1812
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1813
    };
1814
    git(&["init", "-q", "-b", "main"]);
1815
    write(&g, "README.md", b"# Hi\n");
1816
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
1817
    git(&["add", "."]);
1818
    git(&["commit", "-q", "-m", "initial"]);
1819
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1820
    write(&g, "run.sh", b"#!/bin/sh\n");
1821
    #[cfg(unix)]
1822
    {
1823
        use std::os::unix::fs::PermissionsExt;
1824
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1825
    }
1826
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
1827
    git(&["add", "."]);
1828
    git(&[
1829
        "commit",
1830
        "-q",
1831
        "-m",
1832
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
1833
    ]);
1834
    // A branch that edits README, merged back with a conflict-free merge.
1835
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
1836
    write(&g, "README.md", b"# Hi\n\nMore.\n");
1837
    git(&["commit", "-q", "-am", "readme"]);
1838
    git(&["checkout", "-q", "main"]);
1839
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
1840
    // A branch from the initial commit inserting at the same place as
1841
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
1842
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
1843
    git(&["checkout", "-q", "-b", "clash", &initial]);
1844
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
1845
    git(&["commit", "-q", "-am", "clash"]);
1846
    git(&["checkout", "-q", "main"]);
1847
    let _ = std::process::Command::new("git")
1848
        .arg("-C")
1849
        .arg(&g)
1850
        .args(["merge", "-q", "clash"])
1851
        .output();
1852
    write(
1853
        &g,
1854
        "src/lib.rs",
1855
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
1856
    );
1857
    git(&["add", "."]);
1858
    git(&["commit", "-q", "-m", "resolve clash"]);
1859
    git(&["rm", "-q", "logo.png"]);
1860
    git(&["commit", "-q", "-m", "drop logo"]);
1861
    // A rename with a small edit is imported as a move of the same node.
1862
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
1863
    write(
1864
        &g,
1865
        "src/lib2.rs",
1866
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
1867
    );
1868
    git(&["add", "."]);
1869
    git(&["commit", "-q", "-m", "rename lib"]);
1870
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
1871
    // run.sh is the same as in the first parent's tree, but the merged
1872
    // change touched it, so the importer must compare it, not skip it.
1873
    git(&["checkout", "-q", "-b", "discarded"]);
1874
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
1875
    git(&["commit", "-q", "-am", "discarded edit"]);
1876
    git(&["checkout", "-q", "main"]);
1877
    git(&[
1878
        "merge",
1879
        "-q",
1880
        "-s",
1881
        "ours",
1882
        "-m",
1883
        "merge discarded, keeping ours",
1884
        "discarded",
1885
    ]);
1886
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
1887
1888
    let dest = root.join("oxy");
1889
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
1890
    let rep = repo.import_git(&g, "main").unwrap();
1891
    assert_eq!(rep.commits, expected_count);
1892
    assert_eq!(rep.merges, 3);
1893
    assert_eq!(
1894
        fs::read(dest.join("run.sh")).unwrap(),
1895
        b"#!/bin/sh\n",
1896
        "the ours merge kept main's run.sh"
1897
    );
1898
    let v = repo.verify_git_import(&g, "main").unwrap();
1899
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
1900
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
1901
    // The working copy equals the Git tree at main.
1902
    assert_eq!(
1903
        fs::read(dest.join("src/lib2.rs")).unwrap(),
1904
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1905
    );
1906
    assert!(!dest.join("src/lib.rs").exists());
1907
    assert_eq!(
1908
        fs::read(dest.join("README.md")).unwrap(),
1909
        b"# Hi\n\nMore.\n"
1910
    );
1911
    assert!(!dest.join("logo.png").exists());
1912
    #[cfg(unix)]
1913
    {
1914
        use std::os::unix::fs::PermissionsExt;
1915
        assert!(
1916
            fs::metadata(dest.join("run.sh"))
1917
                .unwrap()
1918
                .permissions()
1919
                .mode()
1920
                & 0o111
1921
                != 0
1922
        );
1923
    }
1924
    assert!(
1925
        !repo.snapshot("status").unwrap().changed,
1926
        "clean after import"
1927
    );
1928
    let heads = repo.bookmark_heads().unwrap();
1929
    let st = repo.load_state(&heads).unwrap();
1930
    assert!(!st.materialize().is_conflicted());
1931
    assert_eq!(st.len(), expected_count);
1932
    let tip = repo
1933
        .log()
1934
        .unwrap()
1935
        .into_iter()
1936
        .find(|e| e.change.message.starts_with("rename lib"))
1937
        .unwrap();
1938
    let c = repo.store().get_change(&tip.hash).unwrap();
1939
    assert!(
1940
        c.tree_ops
1941
            .iter()
1942
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
1943
        "{:?}",
1944
        c.tree_ops
1945
    );
1946
    assert!(!c
1947
        .tree_ops
1948
        .iter()
1949
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
1950
    // Messages carry Git trailers; the Change-Id trailer was honoured.
1951
    let log = repo.log().unwrap();
1952
    let second = log
1953
        .iter()
1954
        .find(|e| e.change.message.starts_with("second"))
1955
        .unwrap();
1956
    assert_eq!(
1957
        second.change.change_id,
1958
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
1959
    );
1960
    assert!(second
1961
        .change
1962
        .message
1963
        .contains("Git-Author: Grace <[email protected]>"));
1964
    let resolve = log
1965
        .iter()
1966
        .find(|e| e.change.message.starts_with("resolve clash"))
1967
        .unwrap();
1968
    assert_eq!(
1969
        resolve.change.kind,
1970
        ChangeKind::Resolution,
1971
        "a conflicting Git merge becomes a resolution"
1972
    );
1973
    // Re-importing into another fresh repository gives the same ChangeIds.
1974
    let repo2 = Repo::init(&root.join("oxy2"))
1975
        .unwrap()
1976
        .with_home(root.join("home"));
1977
    repo2.import_git(&g, "main").unwrap();
1978
    // New nodes' identifiers derive from the commit (spec §23), so the
1979
    // re-import is not just the same ChangeIds but the same changes.
1980
    assert_eq!(
1981
        repo2.bookmark_heads().unwrap(),
1982
        repo.bookmark_heads().unwrap()
1983
    );
1984
    let ids: BTreeSet<ChangeId> = repo
1985
        .log()
1986
        .unwrap()
1987
        .iter()
1988
        .filter(|e| !e.is_working_copy)
1989
        .map(|e| e.change.change_id)
1990
        .collect();
1991
    let ids2: BTreeSet<ChangeId> = repo2
1992
        .log()
1993
        .unwrap()
1994
        .iter()
1995
        .filter(|e| !e.is_working_copy)
1996
        .map(|e| e.change.change_id)
1997
        .collect();
1998
    assert_eq!(ids, ids2);
1999
    // Round trip back out to Git reproduces the tip tree.
2000
    let mirror = root.join("mirror.git");
2001
    repo.git_export(&mirror).unwrap();
2002
    let out = std::process::Command::new("git")
2003
        .arg("-C")
2004
        .arg(&mirror)
2005
        .args(["show", "main:src/lib2.rs"])
2006
        .output()
2007
        .unwrap();
2008
    assert_eq!(
2009
        String::from_utf8_lossy(&out.stdout),
2010
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2011
    );
2012
    let out = std::process::Command::new("git")
2013
        .arg("-C")
2014
        .arg(&mirror)
2015
        .args(["show", "main:src/lib.rs"])
2016
        .output()
2017
        .unwrap();
2018
    assert!(
2019
        !out.status.success(),
2020
        "the old path is gone from the export"
2021
    );
2022
}
2023
2024
#[test]
2025
fn checkpoints_accelerate_loading_and_stay_correct() {
2026
    hermetic();
2027
    let dir = tempfile::tempdir().unwrap();
2028
    let root = dir.path();
2029
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2030
    repo.config.set("core.checkpoint-interval", "5").unwrap();
2031
    repo.save_config().unwrap();
2032
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2033
    let mut hashes = Vec::new();
2034
    for i in 0..12 {
2035
        write(
2036
            root,
2037
            "a.txt",
2038
            format!(
2039
                "{}\n",
2040
                (0..=i)
2041
                    .map(|k| k.to_string())
2042
                    .collect::<Vec<_>>()
2043
                    .join("\n")
2044
            )
2045
            .as_bytes(),
2046
        );
2047
        write(root, &format!("f{i}.txt"), b"x\n");
2048
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
2049
    }
2050
    let (_, cp) = repo
2051
        .latest_checkpoint("main")
2052
        .unwrap()
2053
        .expect("automatic checkpoint");
2054
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
2055
    // Loading through the checkpoint equals loading everything.
2056
    let heads = repo.bookmark_heads().unwrap();
2057
    let fast = repo.load_state(&heads).unwrap();
2058
    let full = repo.load_state_full(&heads).unwrap();
2059
    assert_eq!(fast.len(), full.len());
2060
    assert_eq!(fast.heads(), full.heads());
2061
    let (a, b) = (fast.materialize(), full.materialize());
2062
    assert_eq!(
2063
        a.files.keys().collect::<Vec<_>>(),
2064
        b.files.keys().collect::<Vec<_>>()
2065
    );
2066
    for (p, f) in &a.files {
2067
        assert_eq!(f.content, b.files[p].content, "{p}");
2068
    }
2069
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
2070
    // A head set that does not contain the checkpoint's heads falls back.
2071
    assert!(repo
2072
        .load_state_checkpointed(&[hashes[0]])
2073
        .unwrap()
2074
        .is_none());
2075
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
2076
    // Everything else keeps working on top of the checkpoint.
2077
    assert!(!repo.snapshot("status").unwrap().changed);
2078
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
2079
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
2080
    let (r, n, bytes) = repo.checkpoint().unwrap();
2081
    assert!(n >= 12 && bytes > 0);
2082
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
2083
    write(root, "a.txt", b"after\n");
2084
    let h_after = repo.commit("after", &[]).unwrap();
2085
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
2086
    assert!(st.contains(&h_after));
2087
    assert!(
2088
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
2089
    );
2090
    assert_eq!(repo.log().unwrap().len(), 14);
2091
    // Checkpoints survive gc.
2092
    repo.gc(true).unwrap();
2093
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
2094
    assert!(repo
2095
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
2096
        .unwrap()
2097
        .is_some());
2098
}
2099
2100
#[test]
2101
fn quick_status_for_prompts() {
2102
    hermetic();
2103
    let dir = tempfile::tempdir().unwrap();
2104
    let root = dir.path();
2105
    let origin = Repo::init(&root.join("origin")).unwrap();
2106
    let url = root.join("origin").to_string_lossy().to_string();
2107
    let a = Repo::clone(&url, &root.join("a"))
2108
        .unwrap()
2109
        .with_home(root.join("home"));
2110
    let ops_before = a.op_log().unwrap().len();
2111
    let info = a.quick_status().unwrap();
2112
    assert_eq!(
2113
        (
2114
            info.bookmark.as_str(),
2115
            info.heads,
2116
            info.dirty,
2117
            info.conflicted,
2118
            info.ahead,
2119
            info.behind
2120
        ),
2121
        ("main", 0, false, false, Some(0), Some(0))
2122
    );
2123
    write(&root.join("a"), "f.txt", b"f\n");
2124
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
2125
    assert_eq!(
2126
        a.op_log().unwrap().len(),
2127
        ops_before,
2128
        "quick_status records nothing"
2129
    );
2130
    // A snapshotted but uncommitted change is still dirty.
2131
    a.snapshot("status").unwrap();
2132
    assert!(a.quick_status().unwrap().dirty);
2133
    a.commit("f", &[]).unwrap();
2134
    let info = a.quick_status().unwrap();
2135
    assert!(!info.dirty, "clean right after a commit");
2136
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
2137
    assert_eq!(
2138
        info.format("%b %c%d%x%A%D"),
2139
        format!("main {}+1", info.change_id)
2140
    );
2141
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
2142
    // Touching a file without changing it is not dirty; changing content of
2143
    // the same size is.
2144
    let p = root.join("a/f.txt");
2145
    let content = fs::read(&p).unwrap();
2146
    fs::write(&p, &content).unwrap();
2147
    assert!(!a.quick_status().unwrap().dirty);
2148
    fs::write(&p, b"g\n").unwrap();
2149
    assert!(a.quick_status().unwrap().dirty);
2150
    fs::write(&p, b"f\n").unwrap();
2151
    // Push, then a second clone commits and pushes: we are behind.
2152
    assert!(a.push("origin", false).unwrap()[0].ok);
2153
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
2154
    let b = Repo::clone(&url, &root.join("b"))
2155
        .unwrap()
2156
        .with_home(root.join("home-b"));
2157
    write(&root.join("b"), "g.txt", b"g\n");
2158
    b.commit("g", &[]).unwrap();
2159
    b.push("origin", false).unwrap();
2160
    a.fetch("origin").unwrap();
2161
    let info = a.quick_status().unwrap();
2162
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
2163
    assert_eq!(info.format("%A%D"), "-1");
2164
    let _ = origin;
2165
}
2166
2167
#[test]
2168
fn lazy_blobs_are_fetched_on_first_read() {
2169
    hermetic();
2170
    let dir = tempfile::tempdir().unwrap();
2171
    let root = dir.path();
2172
    let origin_dir = root.join("origin");
2173
    let origin = Repo::init(&origin_dir)
2174
        .unwrap()
2175
        .with_home(root.join("home"));
2176
    let url = origin_dir.to_string_lossy().to_string();
2177
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
2178
    write(&origin_dir, "big.bin", &big);
2179
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
2180
    write(&origin_dir, "t.txt", b"t\n");
2181
    let h = origin.commit("blobs", &[]).unwrap();
2182
    let big_ref = Repo::blob_ref(&big);
2183
2184
    // Fetch only (no checkout) with a filter: the big blob stays absent.
2185
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
2186
        .unwrap()
2187
        .with_home(root.join("home"));
2188
    let a = {
2189
        let mut a = a;
2190
        a.config.set("remote.origin.url", &url).unwrap();
2191
        a.config.set("filter.max-blob", "100K").unwrap();
2192
        a.save_config().unwrap();
2193
        a
2194
    };
2195
    assert_eq!(a.config.max_blob, Some(100 * 1024));
2196
    a.fetch("origin").unwrap();
2197
    assert!(a.store().has(&h));
2198
    assert!(!a.store().has(&big_ref), "withheld");
2199
    assert!(
2200
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
2201
        "small blob came along"
2202
    );
2203
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
2204
2205
    // status and commit do not need it: adopt the state, edit a text file, commit.
2206
    let (op_ref, op) = a.head_op().unwrap();
2207
    let mut view = op.view.clone();
2208
    view.bookmarks.insert(
2209
        "main".into(),
2210
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
2211
    );
2212
    a.record_op(&[op_ref], "adopt", view).unwrap();
2213
    // Checkout reads the blob lazily, which fetches it.
2214
    a.checkout(&[h], true, "checkout").unwrap();
2215
    assert!(a.store().has(&big_ref), "fetched on first read");
2216
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
2217
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
2218
    write(&root.join("a"), "t.txt", b"t2\n");
2219
    a.commit("text edit", &[]).unwrap();
2220
2221
    // clone --max-blob records the filter; the checkout fetches lazily.
2222
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
2223
    assert_eq!(b.config.max_blob, Some(1024));
2224
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
2225
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
2226
    assert!(parse_size("lots").is_err());
2227
}
2228
2229
#[test]
2230
fn sparse_checkout_materializes_only_chosen_paths() {
2231
    hermetic();
2232
    let dir = tempfile::tempdir().unwrap();
2233
    let root = dir.path();
2234
    let origin_dir = root.join("origin");
2235
    let origin = Repo::init(&origin_dir)
2236
        .unwrap()
2237
        .with_home(root.join("home"));
2238
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
2239
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
2240
    write(&origin_dir, "docs/guide.md", b"# guide\n");
2241
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
2242
    write(&origin_dir, "docs/logo.png", &logo);
2243
    write(&origin_dir, "README.md", b"# top\n");
2244
    let h1 = origin.commit("tree", &[]).unwrap();
2245
    let url = origin_dir.to_string_lossy().to_string();
2246
2247
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
2248
        .unwrap()
2249
        .with_home(root.join("home"));
2250
    assert_eq!(a.config.sparse_paths, vec!["src"]);
2251
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
2252
    assert!(root.join("a/src/main.rs").exists());
2253
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
2254
    assert!(
2255
        !a.store().has(&Repo::blob_ref(&logo)),
2256
        "out-of-scope blob never fetched"
2257
    );
2258
    assert!(
2259
        !a.snapshot("status").unwrap().changed,
2260
        "out-of-scope files are not removals"
2261
    );
2262
    assert!(!a.quick_status().unwrap().dirty);
2263
2264
    // Edits in scope commit normally and keep the rest of the tree intact.
2265
    write(
2266
        &root.join("a"),
2267
        "src/lib.rs",
2268
        b"pub fn a() {}\npub fn b() {}\n",
2269
    );
2270
    let h2 = a.commit("edit lib", &[]).unwrap();
2271
    let st = a.load_state(&[h2]).unwrap().materialize();
2272
    assert!(
2273
        st.files.contains_key("docs/guide.md"),
2274
        "the state still has everything"
2275
    );
2276
    assert!(a.push("origin", false).unwrap()[0].ok);
2277
    // Files created outside the scope are ignored by status.
2278
    write(&root.join("a"), "docs/new.md", b"ignored\n");
2279
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
2280
2281
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
2282
    let mut a = a;
2283
    a.config.set("filter.paths", "src,docs").unwrap();
2284
    a.save_config().unwrap();
2285
    let r = a
2286
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
2287
        .unwrap();
2288
    assert!(r.written >= 2);
2289
    assert_eq!(
2290
        fs::read(root.join("a/docs/logo.png")).unwrap(),
2291
        logo,
2292
        "now fetched lazily"
2293
    );
2294
    assert!(!root.join("a/README.md").exists());
2295
    // Origin sees the change made under a sparse checkout with the full tree intact.
2296
    origin.pull("origin").err();
2297
    let full = origin
2298
        .load_state(&origin.bookmark_heads().unwrap())
2299
        .unwrap()
2300
        .materialize();
2301
    assert!(
2302
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
2303
    );
2304
    assert!(full.files.contains_key("README.md"));
2305
    let _ = h1;
2306
}
2307
2308
#[test]
2309
fn shallow_clone_and_deepen() {
2310
    hermetic();
2311
    let dir = tempfile::tempdir().unwrap();
2312
    let root = dir.path();
2313
    let origin_dir = root.join("origin");
2314
    let origin = Repo::init(&origin_dir)
2315
        .unwrap()
2316
        .with_home(root.join("home"));
2317
    let mut hashes = Vec::new();
2318
    for i in 0..8 {
2319
        write(
2320
            &origin_dir,
2321
            "a.txt",
2322
            format!(
2323
                "{}\n",
2324
                (0..=i)
2325
                    .map(|k| k.to_string())
2326
                    .collect::<Vec<_>>()
2327
                    .join("\n")
2328
            )
2329
            .as_bytes(),
2330
        );
2331
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
2332
    }
2333
    let url = origin_dir.to_string_lossy().to_string();
2334
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
2335
        .unwrap()
2336
        .with_home(root.join("home"));
2337
    assert!(a.is_shallow());
2338
    assert_eq!(
2339
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
2340
        "0\n1\n2\n3\n4\n5\n6\n7\n"
2341
    );
2342
    assert!(
2343
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
2344
        "three levels present"
2345
    );
2346
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
2347
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
2348
    assert_eq!(
2349
        a.log().unwrap().len(),
2350
        9,
2351
        "the log shows every change from the checkpoint's metadata"
2352
    );
2353
    assert!(!a.snapshot("status").unwrap().changed);
2354
    assert_eq!(a.quick_status().unwrap().heads, 1);
2355
2356
    // Work continues on top of the shallow history and pushes back.
2357
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
2358
    let h_new = a.commit("c8", &[]).unwrap();
2359
    assert!(a.push("origin", false).unwrap()[0].ok);
2360
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
2361
    // Fetching new work from origin into the shallow clone works too.
2362
    write(&origin_dir, "b.txt", b"b\n");
2363
    origin.pull("origin").err();
2364
    let (_, wc) = origin.working_copy().unwrap();
2365
    let _ = wc;
2366
    origin
2367
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
2368
        .unwrap();
2369
    write(&origin_dir, "b.txt", b"b\n");
2370
    let h_b = origin.commit("b", &[]).unwrap();
2371
    let pr = a.pull("origin").unwrap();
2372
    assert!(pr.changed);
2373
    assert!(a.store().has(&h_b));
2374
    assert!(root.join("a/b.txt").exists());
2375
2376
    // Deepening fetches older history until the boundary is gone.
2377
    // Every commit also depends on the change that created the file, so two
2378
    // levels below the boundary hold h4, h3, and the root.
2379
    assert!(a.deepen("origin", 2).unwrap() >= 2);
2380
    assert!(a.store().has(&hashes[3]));
2381
    assert!(a.is_shallow());
2382
    a.deepen("origin", 100).unwrap();
2383
    assert!(!a.is_shallow(), "boundary reached the root");
2384
    assert!(a.store().has(&hashes[0]));
2385
    assert_eq!(
2386
        a.load_state_full(&a.bookmark_heads().unwrap())
2387
            .unwrap()
2388
            .len(),
2389
        10
2390
    );
2391
}
2392
2393
#[test]
2394
fn tags_are_immutable_named_states_and_travel() {
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
    let mut a = Repo::clone(&url, &root.join("a"))
2401
        .unwrap()
2402
        .with_home(root.join("home-a"));
2403
    let (key_a, _) = a
2404
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2405
        .unwrap();
2406
    write(&root.join("a"), "f.txt", b"1\n");
2407
    let h1 = a.commit("one", &[]).unwrap();
2408
    write(&root.join("a"), "f.txt", b"1\n2\n");
2409
    let h2 = a.commit("two", &[]).unwrap();
2410
2411
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
2412
    assert_eq!(
2413
        (t.heads.clone(), t.signer.as_deref()),
2414
        (vec![h1], Some("Ada"))
2415
    );
2416
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2417
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2418
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2419
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2420
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2421
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2422
    assert_eq!(sa.sigs[0].key, key_a);
2423
    // Checkout by tag.
2424
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2425
        .unwrap();
2426
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
2427
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2428
        .unwrap();
2429
2430
    // Push carries the tag; a second attestation for the name is refused.
2431
    let r = a.push("origin", false).unwrap();
2432
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2433
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
2434
    let mut forged = a
2435
        .tag_refs()
2436
        .unwrap()
2437
        .into_iter()
2438
        .find(|t| t.name == "v1")
2439
        .unwrap();
2440
    forged.state = origin
2441
        .store()
2442
        .put_state(&StateObject::new(vec![h2]))
2443
        .unwrap();
2444
    forged.heads = vec![h2];
2445
    forged.attestation = None;
2446
    let r = origin
2447
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2448
        .unwrap();
2449
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2450
2451
    // A clone gets the tag; a later tag arrives on fetch.
2452
    let b = Repo::clone(&url, &root.join("b"))
2453
        .unwrap()
2454
        .with_home(root.join("home-b"));
2455
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2456
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2457
    a.tag_create("v2", &[h2], "second").unwrap();
2458
    a.push("origin", false).unwrap();
2459
    let rep = b.fetch("origin").unwrap();
2460
    assert_eq!(rep.new_tags, 1);
2461
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2462
2463
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2464
    a.policy_init().unwrap();
2465
    a.push("origin", false).unwrap();
2466
    let unattested = crate::protocol::TagRef {
2467
        name: "v3".into(),
2468
        state: origin
2469
            .store()
2470
            .put_state(&StateObject::new(vec![h2]))
2471
            .unwrap(),
2472
        heads: vec![h2],
2473
        attestation: None,
2474
    };
2475
    let r = origin
2476
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2477
        .unwrap();
2478
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2479
    a.tag_create("v3", &[h2], "").unwrap();
2480
    let r = a.push("origin", false).unwrap();
2481
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2482
    assert!(a.gc(true).is_ok());
2483
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
2484
}
2485
2486
#[test]
2487
fn multiple_workspaces_share_a_repository() {
2488
    hermetic();
2489
    let dir = tempfile::tempdir().unwrap();
2490
    let root = dir.path();
2491
    let main_dir = root.join("main");
2492
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2493
    write(&main_dir, "a.txt", b"a\n");
2494
    let h1 = repo.commit("a", &[]).unwrap();
2495
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2496
2497
    // A second workspace elsewhere, checked out on the bookmark.
2498
    let ws_dir = root.join("ws2");
2499
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2500
    assert!(ws_dir.join(".oxy").is_file());
2501
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2502
    assert_ne!(ws.workspace(), repo.workspace());
2503
    let list = repo.workspaces().unwrap();
2504
    assert_eq!(list.len(), 2);
2505
    assert!(list
2506
        .iter()
2507
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
2508
    assert!(!ws.snapshot("status").unwrap().changed);
2509
2510
    // Work in the second workspace: its own working copy, shared bookmark.
2511
    write(&ws_dir, "b.txt", b"b\n");
2512
    let s = ws.snapshot("status").unwrap();
2513
    assert_eq!(s.statuses.len(), 1);
2514
    assert!(
2515
        !repo.snapshot("status").unwrap().changed,
2516
        "the first workspace is untouched"
2517
    );
2518
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2519
    let mut heads = repo.bookmark_heads().unwrap();
2520
    heads.sort();
2521
    let mut want = vec![h1, h2];
2522
    want.sort();
2523
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2524
    assert!(!main_dir.join("b.txt").exists());
2525
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2526
        .unwrap();
2527
    assert!(main_dir.join("b.txt").exists());
2528
2529
    // Reopening from inside the second workspace finds the shared repository.
2530
    let reopened = Repo::open(&ws_dir).unwrap();
2531
    assert_eq!(reopened.workspace(), ws.workspace());
2532
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2533
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2534
2535
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2536
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2537
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2538
    repo.workspace_forget(&ws.workspace()).unwrap();
2539
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2540
    assert!(ws_dir.join("b.txt").exists());
2541
    assert!(
2542
        ws.snapshot("status").is_err(),
2543
        "a forgotten workspace is no longer in the view"
2544
    );
2545
2546
    // The working-copy lock: re-entrant in a thread; a lock whose process
2547
    // is gone is taken over, and a live process's is not, however old.
2548
    let lock = repo.lock_snapshot().unwrap();
2549
    let again = repo.lock_working_copy().unwrap();
2550
    drop(again);
2551
    drop(lock);
2552
    let lock_path = main_dir
2553
        .join(".oxy/workspaces")
2554
        .join(repo.workspace().to_hex())
2555
        .join("lock");
2556
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
2557
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
2558
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
2559
    age(&lock_path);
2560
    assert!(
2561
        !super::workspace::lock_is_stale(&lock_path),
2562
        "a live process keeps its lock"
2563
    );
2564
    fs::write(&lock_path, "4294967295").unwrap();
2565
    age(&lock_path);
2566
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
2567
}
2568
2569
#[test]
2570
fn attributes_binary_eol_nocompress_lockable() {
2571
    hermetic();
2572
    let dir = tempfile::tempdir().unwrap();
2573
    let root = dir.path();
2574
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2575
    write(
2576
        root,
2577
        ".oxyattributes",
2578
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
2579
    );
2580
    write(root, "plain.dat", b"no nul bytes here\n");
2581
    write(root, "notes.txt", b"one\r\ntwo\r\n");
2582
    write(root, "assets/model.bin", b"\0model");
2583
    let h = repo.commit("attrs", &[]).unwrap();
2584
    let snap = repo.load_state(&[h]).unwrap().materialize();
2585
    assert!(
2586
        snap.files["plain.dat"].mode.opaque,
2587
        "binary attribute forces opaque without NUL bytes"
2588
    );
2589
    assert!(
2590
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
2591
        "stored with LF"
2592
    );
2593
    assert!(
2594
        !repo.snapshot("status").unwrap().changed,
2595
        "CRLF on disk equals LF in the state"
2596
    );
2597
    // nocompress chunks pack raw.
2598
    let r = repo.gc(true).unwrap();
2599
    assert!(r.packed.objects > 0);
2600
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
2601
    fs::remove_file(root.join("notes.txt")).unwrap();
2602
    repo.checkout(&[h], true, "co").unwrap();
2603
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
2604
    assert!(fs::metadata(root.join("assets/model.bin"))
2605
        .unwrap()
2606
        .permissions()
2607
        .readonly());
2608
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
2609
    repo.lock_path("assets/model.bin").unwrap();
2610
    assert!(!fs::metadata(root.join("assets/model.bin"))
2611
        .unwrap()
2612
        .permissions()
2613
        .readonly());
2614
    assert!(repo.is_locked("assets/model.bin"));
2615
    write(root, "assets/model.bin", b"\0model2");
2616
    repo.commit("edit model", &[]).unwrap();
2617
    repo.unlock_path("assets/model.bin").unwrap();
2618
    assert!(fs::metadata(root.join("assets/model.bin"))
2619
        .unwrap()
2620
        .permissions()
2621
        .readonly());
2622
    // A later checkout can still overwrite a read-only lockable file.
2623
    repo.checkout(&[h], true, "co").unwrap();
2624
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
2625
}
2626
2627
#[cfg(unix)]
2628
#[test]
2629
fn hooks_can_veto_observe_and_add_dependencies() {
2630
    use std::os::unix::fs::PermissionsExt;
2631
    hermetic();
2632
    let dir = tempfile::tempdir().unwrap();
2633
    let root = dir.path();
2634
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2635
    let hooks = root.join(".oxy/hooks");
2636
    fs::create_dir_all(&hooks).unwrap();
2637
    let hook = |name: &str, body: &str| {
2638
        let p = hooks.join(name);
2639
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
2640
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
2641
    };
2642
    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");
2643
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
2644
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
2645
    hook("pre-push", "echo pushing blocked >&2; exit 3");
2646
    write(root, ".oxyignore", b".last-*\n");
2647
    write(root, "a.txt", b"a\n");
2648
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
2649
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
2650
    let h1 = repo.commit("first", &[]).unwrap();
2651
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
2652
    assert!(
2653
        pre.contains("\"event\":\"pre-commit\"")
2654
            && pre.contains("\"path\":\"a.txt\"")
2655
            && pre.contains("\"message\":\"first\""),
2656
        "{pre}"
2657
    );
2658
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
2659
    assert!(post.contains(&h1.to_hex()), "{post}");
2660
    repo.checkout(&[h1], false, "co").unwrap();
2661
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
2662
        .unwrap()
2663
        .contains("post-checkout"));
2664
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
2665
    repo.save_config().unwrap();
2666
    let err = repo.push("origin", false).unwrap_err().to_string();
2667
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
2668
2669
    // semantic-deps: only when enabled; adds an explicit dependency.
2670
    write(root, "b.txt", b"b\n");
2671
    hook(
2672
        "semantic-deps",
2673
        &format!(
2674
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
2675
            h1.to_hex()
2676
        ),
2677
    );
2678
    let h2 = repo.commit("b without hook", &[]).unwrap();
2679
    assert!(
2680
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
2681
        "hook disabled by default"
2682
    );
2683
    repo.config.set("hooks.semantic-deps", "true").unwrap();
2684
    repo.save_config().unwrap();
2685
    write(root, "c.txt", b"c\n");
2686
    let h3 = repo.commit("c with hook", &[]).unwrap();
2687
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
2688
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
2689
    assert!(
2690
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
2691
        "{sem}"
2692
    );
2693
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
2694
}
2695
2696
#[test]
2697
fn amend_into_older_change_and_split() {
2698
    hermetic();
2699
    let dir = tempfile::tempdir().unwrap();
2700
    let root = dir.path();
2701
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2702
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2703
        .unwrap();
2704
    repo.set_user_config("core.sign", "change").unwrap();
2705
    write(root, "a.txt", b"one\ntwo\n");
2706
    let h0 = repo.commit("base", &[]).unwrap();
2707
    write(root, "a.txt", b"one\nTWO\n");
2708
    let h1 = repo.commit("edit two", &[]).unwrap();
2709
    write(root, "a.txt", b"one\nTWO\nthree\n");
2710
    let h2 = repo.commit("add three", &[]).unwrap();
2711
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
2712
2713
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
2714
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2715
    let h1b = repo.amend_into(&h1, None).unwrap();
2716
    assert_ne!(h1b, h1);
2717
    let c1b = repo.store().get_change(&h1b).unwrap();
2718
    assert_eq!(c1b.change_id, id1);
2719
    assert_eq!(c1b.deps, vec![h0]);
2720
    assert!(matches!(
2721
        repo.verify_change(&h1b).unwrap(),
2722
        SignatureStatus::Valid { .. }
2723
    ));
2724
    let heads = repo.bookmark_heads().unwrap();
2725
    assert_eq!(heads.len(), 1);
2726
    let top = repo.store().get_change(&heads[0]).unwrap();
2727
    assert_eq!(top.message, "add three");
2728
    assert_eq!(
2729
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
2730
        [h0, h1b].into_iter().collect(),
2731
        "depends on the file's creator and the rewritten line"
2732
    );
2733
    let snap = repo.load_state(&heads).unwrap().materialize();
2734
    assert!(
2735
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
2736
    );
2737
    assert!(
2738
        !repo.snapshot("status").unwrap().changed,
2739
        "the working copy is clean after folding"
2740
    );
2741
    // Only h1b's own state shows the fix without "three".
2742
    let only = repo.load_state(&[h1b]).unwrap().materialize();
2743
    assert!(
2744
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
2745
    );
2746
    assert_eq!(repo.log().unwrap().len(), 4);
2747
2748
    // An edit to a line introduced by h2 cannot fold into h1.
2749
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
2750
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
2751
    assert!(err.contains("introduced after"), "{err}");
2752
    assert!(
2753
        repo.snapshot("status").unwrap().statuses.len() == 1,
2754
        "nothing was changed by the refusal"
2755
    );
2756
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2757
2758
    // Split the head that touches two files.
2759
    write(root, "b.txt", b"b\n");
2760
    write(root, "c.txt", b"c\n");
2761
    let h3 = repo.commit("b and c", &[]).unwrap();
2762
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
2763
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
2764
    let c_1 = repo.store().get_change(&p1).unwrap();
2765
    let c_2 = repo.store().get_change(&p2).unwrap();
2766
    assert!(c_1.message.contains("part 1: b.txt"));
2767
    assert_eq!(c_2.change_id, id3);
2768
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2769
    assert!(
2770
        heads.contains(&p1) && heads.contains(&p2),
2771
        "independent parts are both heads"
2772
    );
2773
    let snap = repo
2774
        .load_state(&repo.bookmark_heads().unwrap())
2775
        .unwrap()
2776
        .materialize();
2777
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
2778
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
2779
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
2780
    assert!(!repo.snapshot("status").unwrap().changed);
2781
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
2782
    let _ = h2;
2783
}
2784
2785
#[test]
2786
fn identity_lifecycle() {
2787
    hermetic();
2788
    let dir = tempfile::tempdir().unwrap();
2789
    let root = dir.path();
2790
    let origin = Repo::init(&root.join("origin")).unwrap();
2791
    let url = root.join("origin").to_string_lossy().to_string();
2792
    let mut a = Repo::clone(&url, &root.join("a"))
2793
        .unwrap()
2794
        .with_home(root.join("home-a"));
2795
    a.set_user_config("core.sign", "change").unwrap();
2796
    let (key_a, _) = a
2797
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2798
        .unwrap();
2799
    write(&root.join("a"), "a.txt", b"a\n");
2800
    let h1 = a.commit("one", &[]).unwrap();
2801
    assert!(a.policy_init().unwrap().applied);
2802
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2803
2804
    // Expiry: an identity that had expired when the change was made does not authenticate it.
2805
    let mut e = Repo::init(&root.join("e"))
2806
        .unwrap()
2807
        .with_home(root.join("home-e"));
2808
    e.set_user_config("core.sign", "change").unwrap();
2809
    e.create_identity_with(
2810
        "Eve",
2811
        "[email protected]",
2812
        IdentityScope::User,
2813
        Some(Hlc::now().wall_ms - 1),
2814
    )
2815
    .unwrap();
2816
    write(&root.join("e"), "e.txt", b"e\n");
2817
    let he = e.commit("late", &[]).unwrap();
2818
    assert!(
2819
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
2820
    );
2821
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
2822
    let r = e
2823
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
2824
        .unwrap();
2825
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
2826
    write(&root.join("e"), "e.txt", b"e2\n");
2827
    let he2 = e.commit("in time", &[]).unwrap();
2828
    assert!(
2829
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
2830
    );
2831
2832
    // Rotation: a fresh key; the old change still verifies; the policy follows.
2833
    let r = a.rotate_identity().unwrap();
2834
    assert_eq!(r.old, key_a);
2835
    assert_eq!(a.config.author_key, Some(r.new));
2836
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
2837
    assert!(r.policy.as_ref().unwrap().applied);
2838
    let (_, sp) = a.current_policy().unwrap().unwrap();
2839
    assert_eq!(
2840
        (sp.policy.serial, sp.policy.roots.clone()),
2841
        (2, vec![r.new])
2842
    );
2843
    assert!(
2844
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
2845
        "superseded, not revoked"
2846
    );
2847
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
2848
    assert!(
2849
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
2850
    );
2851
    write(&root.join("a"), "a.txt", b"a2\n");
2852
    let h2 = a.commit("two", &[]).unwrap();
2853
    assert!(
2854
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
2855
    );
2856
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
2857
    let res = a.push("origin", false).unwrap();
2858
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2859
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
2860
    let key_a = r.new;
2861
2862
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
2863
    // identity object, so Ada's KeyId changes while her keys stay the same.
2864
    let mut b = Repo::clone(&url, &root.join("b"))
2865
        .unwrap()
2866
        .with_home(root.join("home-b"));
2867
    let (key_b, id_b) = b
2868
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2869
        .unwrap();
2870
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
2871
    assert_eq!(r.old, key_a);
2872
    let key_a2 = r.new;
2873
    assert_eq!(
2874
        a.identity(&key_a2).unwrap().delegates,
2875
        vec![Delegate::full(key_b)]
2876
    );
2877
    assert_eq!(
2878
        a.identity(&key_a2).unwrap().ed25519_pk,
2879
        a.identity(&key_a).unwrap().ed25519_pk
2880
    );
2881
    assert!(
2882
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
2883
        "already a delegate"
2884
    );
2885
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2886
    write(&root.join("a"), "a.txt", b"a3\n");
2887
    let h3 = a.commit("three", &[]).unwrap();
2888
    assert!(
2889
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
2890
        "the same secret signs under the new KeyId"
2891
    );
2892
    // A change authored by Ada but signed only by Bob verifies through the delegation.
2893
    a.set_user_config("core.sign", "seal").unwrap();
2894
    write(&root.join("a"), "a.txt", b"a4\n");
2895
    let h4 = a.commit("four", &[]).unwrap();
2896
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
2897
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
2898
    a.store()
2899
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
2900
        .unwrap();
2901
    assert!(
2902
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
2903
    );
2904
    a.set_user_config("core.sign", "change").unwrap();
2905
    // Withdrawing the delegation re-issues the identity again.
2906
    let r = a.delegate_remove(&key_b).unwrap();
2907
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
2908
    assert!(a.delegate_remove(&key_b).is_err());
2909
    let key_a3 = r.new;
2910
    let res = a.push("origin", false).unwrap();
2911
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2912
2913
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
2914
    // both applied under the old threshold of 1. A grant then needs Bob too.
2915
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
2916
    assert!(a.policy_root_add(id_b.clone()).is_err());
2917
    assert!(a.policy_set_threshold(3).is_err());
2918
    assert!(a.policy_set_threshold(2).unwrap().applied);
2919
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2920
    b.pull("origin").unwrap();
2921
    assert_eq!(
2922
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
2923
        2
2924
    );
2925
    let mut c = Repo::init(&root.join("c"))
2926
        .unwrap()
2927
        .with_home(root.join("home-c"));
2928
    let (key_c, id_c) = c
2929
        .create_identity("Cy", "[email protected]", IdentityScope::User)
2930
        .unwrap();
2931
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
2932
    let proposal = a.policy_grant(id_c, None).unwrap();
2933
    assert!(!proposal.applied && proposal.sigs.len() == 1);
2934
    assert_eq!(proposal.policy.serial, serial_before + 1);
2935
    assert_eq!(
2936
        a.current_policy().unwrap().unwrap().1.policy.serial,
2937
        serial_before,
2938
        "a proposal changes nothing yet"
2939
    );
2940
    // Bob signs the proposal, handed over as a file, and it applies for him.
2941
    let bytes = proposal.signed().encode();
2942
    let signed = b
2943
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
2944
        .unwrap();
2945
    assert!(signed.applied && signed.sigs.len() == 2);
2946
    assert!(b
2947
        .current_policy()
2948
        .unwrap()
2949
        .unwrap()
2950
        .1
2951
        .policy
2952
        .authorizes(&key_c, "main"));
2953
    assert!(
2954
        b.policy_sign(signed.signed()).is_err(),
2955
        "a stale proposal is refused"
2956
    );
2957
    // Bob publishes it and Ada picks it up.
2958
    assert!(b
2959
        .push("origin", false)
2960
        .unwrap()
2961
        .iter()
2962
        .any(|x| x.name == "policy" && x.ok));
2963
    a.pull("origin").unwrap();
2964
    assert_eq!(
2965
        a.current_policy().unwrap().unwrap().1.policy.serial,
2966
        serial_before + 1
2967
    );
2968
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
2969
    assert!(a.policy_revoke(&key_a3).is_err());
2970
    let u = a
2971
        .revoke_identity(&key_c, "left the project")
2972
        .unwrap()
2973
        .unwrap();
2974
    assert!(!u.applied);
2975
    assert!(a.is_revoked(&key_c).unwrap());
2976
    assert!(!b.is_revoked(&key_c).unwrap());
2977
    let u = b.policy_sign(u.signed()).unwrap();
2978
    assert!(u.applied && u.policy.is_revoked(&key_c));
2979
    assert!(b.is_revoked(&key_c).unwrap());
2980
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
2981
    assert!(
2982
        b.policy_revoke(&key_a3).is_err(),
2983
        "would leave one root for a threshold of 2"
2984
    );
2985
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
2986
    let key_c_own = c.config.author_key.unwrap();
2987
    assert!(c
2988
        .revoke_identity(&key_c_own, "lost laptop")
2989
        .unwrap()
2990
        .is_none());
2991
    assert!(c.is_revoked(&key_c_own).unwrap());
2992
    assert_eq!(key_c_own, key_c);
2993
}
2994
2995
#[test]
2996
fn renames_are_detected_and_tracked_as_moves() {
2997
    hermetic();
2998
    let dir = tempfile::tempdir().unwrap();
2999
    let root = dir.path();
3000
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3001
    write(
3002
        root,
3003
        "src/old.rs",
3004
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
3005
    );
3006
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
3007
    write(root, "tiny.txt", b"x\n");
3008
    let h1 = repo.commit("base", &[]).unwrap();
3009
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
3010
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
3011
3012
    // Rename with a small edit, a binary moved unchanged, and a rewrite
3013
    // that shares nothing with the removed file.
3014
    fs::remove_file(root.join("src/old.rs")).unwrap();
3015
    write(
3016
        root,
3017
        "lib/new.rs",
3018
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
3019
    );
3020
    fs::remove_file(root.join("img.bin")).unwrap();
3021
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
3022
    fs::remove_file(root.join("tiny.txt")).unwrap();
3023
    write(root, "other.txt", b"completely different\n");
3024
    let snap = repo.snapshot("status").unwrap();
3025
    let statuses: Vec<(&str, ChangeStatus)> = snap
3026
        .statuses
3027
        .iter()
3028
        .map(|s| (s.path.as_str(), s.status))
3029
        .collect();
3030
    assert_eq!(
3031
        statuses,
3032
        vec![
3033
            ("assets/img.bin", ChangeStatus::Renamed),
3034
            ("lib/new.rs", ChangeStatus::Renamed),
3035
            ("other.txt", ChangeStatus::Added),
3036
            ("src", ChangeStatus::Removed),
3037
            ("tiny.txt", ChangeStatus::Removed)
3038
        ]
3039
    );
3040
    let h2 = repo.commit("move things", &[]).unwrap();
3041
    let c = repo.store().get_change(&h2).unwrap();
3042
    let moves: Vec<_> = c
3043
        .tree_ops
3044
        .iter()
3045
        .filter(|op| matches!(op, TreeOp::Move { .. }))
3046
        .collect();
3047
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
3048
    assert!(c.tree_ops.iter().any(
3049
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
3050
    ));
3051
    assert!(c.tree_ops.iter().any(
3052
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
3053
    ));
3054
    let snap = repo.load_state(&[h2]).unwrap().materialize();
3055
    assert_eq!(
3056
        snap.files["lib/new.rs"].node, node_old,
3057
        "the node survives the rename"
3058
    );
3059
    assert!(
3060
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
3061
    );
3062
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
3063
    assert!(render_change(
3064
        &c,
3065
        &repo.load_state(&[h1]).unwrap(),
3066
        &repo.load_state(&[h1]).unwrap().materialize()
3067
    )
3068
    .contains("R "));
3069
    // A fresh checkout reproduces the tree.
3070
    let other = tempfile::tempdir().unwrap();
3071
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
3072
    assert_eq!(
3073
        fs::read(other.path().join("lib/new.rs")).unwrap(),
3074
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
3075
    );
3076
    assert!(!other.path().join("src").exists());
3077
    assert!(!clone.snapshot("status").unwrap().changed);
3078
    // Similarity is line based, byte weighted.
3079
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
3080
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
3081
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
3082
    assert_eq!(similarity(b"", b"x\n"), 0);
3083
}
3084
3085
#[test]
3086
fn git_fetch_and_push_round_trip() {
3087
    hermetic();
3088
    if std::process::Command::new("git")
3089
        .arg("--version")
3090
        .output()
3091
        .is_err()
3092
    {
3093
        eprintln!("git not installed; skipping");
3094
        return;
3095
    }
3096
    let dir = tempfile::tempdir().unwrap();
3097
    let root = dir.path();
3098
    let git_in = |d: &Path, args: &[&str]| -> String {
3099
        let out = std::process::Command::new("git")
3100
            .arg("-C")
3101
            .arg(d)
3102
            .args([
3103
                "-c",
3104
                "user.name=Grace",
3105
                "-c",
3106
                "[email protected]",
3107
                "-c",
3108
                "commit.gpgsign=false",
3109
            ])
3110
            .args(args)
3111
            .output()
3112
            .unwrap();
3113
        assert!(
3114
            out.status.success(),
3115
            "git {args:?}: {}",
3116
            String::from_utf8_lossy(&out.stderr)
3117
        );
3118
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3119
    };
3120
    // A bare "remote" and a work tree that pushes to it.
3121
    let remote = root.join("remote.git");
3122
    fs::create_dir_all(&remote).unwrap();
3123
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
3124
    let work = root.join("work");
3125
    git_in(
3126
        root,
3127
        &[
3128
            "clone",
3129
            "-q",
3130
            remote.to_str().unwrap(),
3131
            work.to_str().unwrap(),
3132
        ],
3133
    );
3134
    git_in(&work, &["checkout", "-q", "-b", "main"]);
3135
    write(&work, "README.md", b"# Project\n");
3136
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
3137
    git_in(&work, &["add", "."]);
3138
    git_in(&work, &["commit", "-q", "-m", "initial"]);
3139
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
3140
    git_in(&work, &["commit", "-q", "-am", "second"]);
3141
    git_in(&work, &["push", "-q", "origin", "main"]);
3142
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
3143
3144
    // Fetch into a fresh oxy repository.
3145
    let o = root.join("oxy");
3146
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
3147
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3148
        .unwrap();
3149
    let url = remote.to_string_lossy().to_string();
3150
    let r = repo.git_fetch(&url, "main").unwrap();
3151
    assert_eq!((r.commits, r.heads), (2, 1));
3152
    assert_eq!(
3153
        fs::read(o.join("src/lib.rs")).unwrap(),
3154
        b"pub fn a() {}\npub fn b() {}\n"
3155
    );
3156
    assert!(!repo.snapshot("status").unwrap().changed);
3157
    assert_eq!(
3158
        repo.git_fetch(&url, "main").unwrap().commits,
3159
        0,
3160
        "nothing new"
3161
    );
3162
3163
    // An oxy change, pushed back: one commit on top of the Git tip.
3164
    write(
3165
        &o,
3166
        "src/lib.rs",
3167
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
3168
    );
3169
    write(&o, "NOTES.md", b"from oxy\n");
3170
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
3171
    let r = repo.git_push(&url, "main").unwrap();
3172
    assert_eq!(r.exported, 1, "{r:?}");
3173
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3174
    assert_eq!(
3175
        git_in(&work, &["log", "--format=%s", "main"]),
3176
        "add c and notes\nsecond\ninitial"
3177
    );
3178
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
3179
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
3180
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
3181
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
3182
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
3183
    assert_eq!(
3184
        repo.git_push(&url, "main").unwrap().exported,
3185
        0,
3186
        "already pushed"
3187
    );
3188
3189
    // Git moves on; pushing without fetching is refused, fetching brings
3190
    // the commit in and the working copy follows.
3191
    write(&work, "README.md", b"# Project\n\nMore.\n");
3192
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
3193
    git_in(&work, &["push", "-q", "origin", "main"]);
3194
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
3195
    assert!(repo
3196
        .git_push(&url, "main")
3197
        .unwrap_err()
3198
        .to_string()
3199
        .contains("fetch"));
3200
    let r = repo.git_fetch(&url, "main").unwrap();
3201
    assert_eq!(
3202
        (r.commits, r.heads),
3203
        (1, 2),
3204
        "the Git change and the oxy change commute"
3205
    );
3206
    assert_eq!(
3207
        fs::read(o.join("README.md")).unwrap(),
3208
        b"# Project\n\nMore.\n"
3209
    );
3210
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
3211
    assert!(!repo.snapshot("status").unwrap().changed);
3212
    // Another oxy change pushes on top of Git's newest commit.
3213
    write(&o, "NOTES.md", b"from oxy\nagain\n");
3214
    repo.commit("notes again", &[]).unwrap();
3215
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
3216
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3217
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
3218
    assert_eq!(
3219
        fs::read(work.join("NOTES.md")).unwrap(),
3220
        b"from oxy\nagain\n"
3221
    );
3222
    assert_eq!(
3223
        git_in(&work, &["log", "--format=%s", "main"])
3224
            .lines()
3225
            .count(),
3226
        5
3227
    );
3228
}
3229
3230
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
3231
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
3232
#[test]
3233
#[ignore]
3234
fn bench_one_gibibyte_file() {
3235
    hermetic();
3236
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
3237
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
3238
        Some(d) => tempfile::tempdir_in(d).unwrap(),
3239
        None => tempfile::tempdir().unwrap(),
3240
    };
3241
    let root = dir.path();
3242
    let repo = Repo::init(&root.join("r"))
3243
        .unwrap()
3244
        .with_home(root.join("home"));
3245
    let size = 1usize << 30;
3246
    let mut data = vec![0u8; size];
3247
    let mut x = 0x9e3779b97f4a7c15u64;
3248
    for chunk in data.chunks_mut(8) {
3249
        x ^= x << 13;
3250
        x ^= x >> 7;
3251
        x ^= x << 17;
3252
        let b = x.to_le_bytes();
3253
        chunk.copy_from_slice(&b[..chunk.len()]);
3254
    }
3255
    let t = std::time::Instant::now();
3256
    write(&root.join("r"), "big.bin", &data);
3257
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
3258
    let t = std::time::Instant::now();
3259
    let h = repo.commit("big", &[]).unwrap();
3260
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
3261
    let t = std::time::Instant::now();
3262
    assert!(!repo.snapshot("status").unwrap().changed);
3263
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
3264
    let t = std::time::Instant::now();
3265
    let objects = repo.store().list().unwrap().len();
3266
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
3267
    let t = std::time::Instant::now();
3268
    let g = repo.gc(true).unwrap();
3269
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
3270
    let t = std::time::Instant::now();
3271
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
3272
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
3273
    let t = std::time::Instant::now();
3274
    let back = fs::read(root.join("c/big.bin")).unwrap();
3275
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
3276
    eprintln!("read back and verify: {:.2?}", t.elapsed());
3277
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
3278
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
3279
    eprintln!(
3280
        "store size: {:.1} MiB for 1 GiB of data",
3281
        store_bytes as f64 / (1024.0 * 1024.0)
3282
    );
3283
}
3284
3285
fn walkdir_size(p: &Path) -> u64 {
3286
    let mut total = 0;
3287
    if let Ok(rd) = fs::read_dir(p) {
3288
        for e in rd.flatten() {
3289
            let path = e.path();
3290
            if path.is_dir() {
3291
                total += walkdir_size(&path);
3292
            } else if let Ok(m) = fs::metadata(&path) {
3293
                total += m.len();
3294
            }
3295
        }
3296
    }
3297
    total
3298
}
3299
3300
/// An opaque file whose size and mtime match the manifest is not read on
3301
/// the next snapshot: its blob comes from the manifest's stat cache.
3302
#[cfg(unix)]
3303
#[test]
3304
fn stat_cache_skips_reading_unchanged_opaque_files() {
3305
    use std::os::unix::fs::PermissionsExt;
3306
    hermetic();
3307
    let dir = tempfile::tempdir().unwrap();
3308
    let root = dir.path();
3309
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3310
    let mut big = vec![0u8; 300 * 1024];
3311
    for (i, b) in big.iter_mut().enumerate() {
3312
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
3313
    }
3314
    big[0] = 0;
3315
    write(root, "big.bin", &big);
3316
    write(root, "a.txt", b"text\n");
3317
    let h1 = repo.commit("base", &[]).unwrap();
3318
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3319
    assert!(
3320
        m.entries["big.bin"].blob.is_some(),
3321
        "opaque files record their blob"
3322
    );
3323
    assert!(m.entries["a.txt"].blob.is_none());
3324
    let blob = m.entries["big.bin"].blob.unwrap();
3325
    assert!(repo.store().has(&blob));
3326
3327
    // Files modified within two seconds of the manifest are racy and still
3328
    // read; age the file so the cache applies, then snapshot to record it.
3329
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
3330
    fs::File::options()
3331
        .write(true)
3332
        .open(root.join("big.bin"))
3333
        .unwrap()
3334
        .set_modified(old)
3335
        .unwrap();
3336
    assert!(!repo.snapshot("status").unwrap().changed);
3337
    // Now the file cannot be read at all; the snapshot succeeds without it.
3338
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
3339
    let snap = repo.snapshot("status").unwrap();
3340
    assert!(
3341
        !snap.changed && snap.statuses.is_empty(),
3342
        "{:?}",
3343
        snap.statuses
3344
    );
3345
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
3346
    // A real change (new mtime, new content) is seen and committed correctly.
3347
    let mut big2 = big.clone();
3348
    big2[10] ^= 0xff;
3349
    write(root, "big.bin", &big2);
3350
    let snap = repo.snapshot("status").unwrap();
3351
    assert_eq!(
3352
        snap.statuses
3353
            .iter()
3354
            .map(|s| (s.path.as_str(), s.status))
3355
            .collect::<Vec<_>>(),
3356
        vec![("big.bin", ChangeStatus::Modified)]
3357
    );
3358
    let h2 = repo.commit("edit", &[]).unwrap();
3359
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3360
    assert_eq!(
3361
        files["big.bin"].content,
3362
        FileContent::Opaque {
3363
            blobs: vec![Repo::blob_ref(&big2)]
3364
        }
3365
    );
3366
    // Checkout writes a manifest with blobs too, so the next status is cached.
3367
    repo.checkout(&[h1], false, "checkout").unwrap();
3368
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3369
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
3370
    assert!(!repo.snapshot("status").unwrap().changed);
3371
}
3372
3373
#[test]
3374
fn status_json_lists_conflicts_with_contributors() {
3375
    hermetic();
3376
    let dir = tempfile::tempdir().unwrap();
3377
    let root = dir.path();
3378
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3379
    write(root, "a.txt", b"one\n");
3380
    let h1 = repo.commit("base", &[]).unwrap();
3381
    write(root, "a.txt", b"one\nleft\n");
3382
    let ha = repo.commit("left", &[]).unwrap();
3383
    repo.checkout(&[h1], true, "checkout").unwrap();
3384
    write(root, "a.txt", b"one\nright\n");
3385
    let hb = repo.commit("right", &[]).unwrap();
3386
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
3387
    let snap = repo.snapshot("status").unwrap();
3388
    assert!(snap.base_snapshot.is_conflicted());
3389
    let json = repo.status_json(&snap).unwrap();
3390
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
3391
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
3392
    assert!(json.contains("\"conflicted\":true"), "{json}");
3393
    assert!(
3394
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3395
        "{json}"
3396
    );
3397
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3398
    assert!(json.contains("\"resolved\":false"), "{json}");
3399
    assert!(json.starts_with('{') && json.ends_with('}'));
3400
    // Resolve and the report says so; a clean copy has no conflicts.
3401
    write(root, "a.txt", b"one\nleft\nright\n");
3402
    let snap = repo.snapshot("status").unwrap();
3403
    let json = repo.status_json(&snap).unwrap();
3404
    assert!(json.contains("\"resolved\":true"), "{json}");
3405
    repo.commit("resolve", &[]).unwrap();
3406
    let snap = repo.snapshot("status").unwrap();
3407
    let json = repo.status_json(&snap).unwrap();
3408
    assert!(
3409
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3410
        "{json}"
3411
    );
3412
}
3413
3414
#[test]
3415
fn ignore_rules_do_not_untrack_files() {
3416
    hermetic();
3417
    let dir = tempfile::tempdir().unwrap();
3418
    let root = dir.path();
3419
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3420
    write(root, "src.c", b"int x;\n");
3421
    write(root, "build/out.o", b"\0obj");
3422
    write(root, "sub/keep.log", b"keep\n");
3423
    write(root, "sub/junk.log", b"junk\n");
3424
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3425
    let snap = repo.snapshot("status").unwrap();
3426
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3427
    assert_eq!(
3428
        added,
3429
        vec![".oxyignore", "src.c", "sub/keep.log"],
3430
        "anchored, glob, and negated rules"
3431
    );
3432
    let h1 = repo.commit("base", &[]).unwrap();
3433
    // Ignoring a tracked file changes nothing about it.
3434
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3435
    let snap = repo.snapshot("status").unwrap();
3436
    assert_eq!(
3437
        snap.statuses
3438
            .iter()
3439
            .map(|s| s.path.as_str())
3440
            .collect::<Vec<_>>(),
3441
        vec![".oxyignore"]
3442
    );
3443
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
3444
    assert!(repo
3445
        .load_state(&[h2])
3446
        .unwrap()
3447
        .materialize()
3448
        .files
3449
        .contains_key("src.c"));
3450
    // Its edits are still seen, by status and by the prompt.
3451
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3452
    write(root, "src.c", b"int x, y;\n");
3453
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3454
    let snap = repo.snapshot("status").unwrap();
3455
    assert_eq!(
3456
        snap.statuses
3457
            .iter()
3458
            .map(|s| (s.path.as_str(), s.status))
3459
            .collect::<Vec<_>>(),
3460
        vec![("src.c", ChangeStatus::Modified)]
3461
    );
3462
    let h3 = repo.commit("edit src.c", &[]).unwrap();
3463
    assert!(
3464
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3465
    );
3466
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3467
    fs::remove_file(root.join("src.c")).unwrap();
3468
    let snap = repo.snapshot("status").unwrap();
3469
    assert_eq!(
3470
        snap.statuses
3471
            .iter()
3472
            .map(|s| (s.path.as_str(), s.status))
3473
            .collect::<Vec<_>>(),
3474
        vec![("src.c", ChangeStatus::Removed)]
3475
    );
3476
    repo.checkout(&[h3], true, "checkout").unwrap();
3477
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3478
    assert!(!repo.snapshot("status").unwrap().changed);
3479
    let _ = h1;
3480
}
3481
3482
#[test]
3483
fn split_works_on_non_heads_by_node() {
3484
    hermetic();
3485
    let dir = tempfile::tempdir().unwrap();
3486
    let root = dir.path();
3487
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3488
    write(root, "a.txt", b"one\n");
3489
    write(root, "junk/x.lock", b"lock\n");
3490
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3491
    write(root, "a.txt", b"one\ntwo\n");
3492
    let h2 = repo.commit("more work", &[]).unwrap();
3493
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3494
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3495
    // h1 is not a head: split it by node.
3496
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3497
    assert_ne!(h1b, h1);
3498
    assert_eq!(
3499
        repo.store().get_change(&h1b).unwrap().change_id,
3500
        id1,
3501
        "the rest keeps the ChangeId"
3502
    );
3503
    let junk = repo.store().get_change(&hj).unwrap();
3504
    assert!(junk.tree_ops.iter().all(
3505
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3506
    ));
3507
    let heads = repo.bookmark_heads().unwrap();
3508
    assert!(
3509
        heads.contains(&hj),
3510
        "the split-off part is a head of its own"
3511
    );
3512
    let snap = repo.load_state(&heads).unwrap().materialize();
3513
    assert!(
3514
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3515
        "the dependent was rewritten onto the new hash"
3516
    );
3517
    assert!(snap.files.contains_key("junk/x.lock"));
3518
    let h2b = heads
3519
        .iter()
3520
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3521
        .copied()
3522
        .unwrap();
3523
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3524
    assert!(!repo.snapshot("status").unwrap().changed);
3525
    // Abandoning the split-off head removes the junk from history.
3526
    repo.abandon(&hj).unwrap();
3527
    let heads = repo.bookmark_heads().unwrap();
3528
    let snap = repo.load_state(&heads).unwrap().materialize();
3529
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3530
    assert!(snap.files.contains_key("a.txt"));
3531
    // A dependent that touches the split-off paths blocks the split.
3532
    write(root, "junk/y.lock", b"y\n");
3533
    let hb = repo.commit("junk base", &[]).unwrap();
3534
    write(root, "junk/y.lock", b"yy\n");
3535
    write(root, "b.txt", b"b\n");
3536
    repo.commit("touches junk", &[]).unwrap();
3537
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3538
    assert!(err.contains("depends on the split-off paths"), "{err}");
3539
}
3540
3541
#[test]
3542
fn bookmarks_switch_merge_and_push() {
3543
    hermetic();
3544
    let dir = tempfile::tempdir().unwrap();
3545
    let root = dir.path();
3546
    let origin = Repo::init(&root.join("origin")).unwrap();
3547
    let url = root.join("origin").to_string_lossy().to_string();
3548
    let mut repo = Repo::clone(&url, &root.join("r"))
3549
        .unwrap()
3550
        .with_home(root.join("home"));
3551
    let r = root.join("r");
3552
    write(&r, "a.txt", b"a\n");
3553
    let h_a = repo.commit("a", &[]).unwrap();
3554
    assert!(repo.push("origin", false).unwrap()[0].ok);
3555
3556
    // A bookmark at the working copy's base, then work on it.
3557
    assert!(repo.bookmark_create("bad name..", None).is_err());
3558
    assert!(repo.bookmark_create("-x", None).is_err());
3559
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3560
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3561
    repo.bookmark_switch("feature", false).unwrap();
3562
    assert_eq!(repo.config.bookmark, "feature");
3563
    write(&r, "a.txt", b"a\nb\n");
3564
    write(&r, "b.txt", b"b\n");
3565
    let h_b = repo.commit("b on feature", &[]).unwrap();
3566
    assert_eq!(
3567
        repo.bookmark_heads().unwrap(),
3568
        vec![h_b],
3569
        "b edits a.txt, so it depends on a"
3570
    );
3571
    assert_eq!(
3572
        repo.resolve_heads("main").unwrap(),
3573
        vec![h_a],
3574
        "main is untouched"
3575
    );
3576
    assert_eq!(
3577
        repo.resolve_change("feature").unwrap(),
3578
        h_b,
3579
        "a one-head bookmark names its change"
3580
    );
3581
    // Reopening keeps the workspace's bookmark.
3582
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
3583
    assert_eq!(reopened.config.bookmark, "feature");
3584
    // Back to main: b.txt goes away; work there.
3585
    repo.bookmark_switch("main", false).unwrap();
3586
    assert!(!r.join("b.txt").exists());
3587
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
3588
    write(&r, "c.txt", b"c\n");
3589
    let h_c = repo.commit("c on main", &[]).unwrap();
3590
    let list = repo.bookmarks().unwrap();
3591
    assert_eq!(
3592
        list.iter()
3593
            .map(|b| (b.name.as_str(), b.current))
3594
            .collect::<Vec<_>>(),
3595
        vec![("feature", false), ("main", true)]
3596
    );
3597
    assert_eq!(
3598
        list.iter().find(|b| b.name == "main").unwrap().ahead,
3599
        Some(1),
3600
        "c is not on origin yet"
3601
    );
3602
    // Merge feature into main: the union, both heads, no merge change.
3603
    let m = repo.merge("feature").unwrap();
3604
    assert!(m.changed && m.checked_out);
3605
    let mut want = vec![h_b, h_c];
3606
    want.sort();
3607
    assert_eq!(m.heads, want);
3608
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
3609
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
3610
    assert!(repo.merge("main").is_err());
3611
    // The other bookmark can be pushed by name and appears at origin.
3612
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
3613
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
3614
    assert!(repo.push("origin", false).unwrap()[0].ok);
3615
    assert_eq!(
3616
        repo.bookmarks()
3617
            .unwrap()
3618
            .iter()
3619
            .find(|b| b.name == "main")
3620
            .unwrap()
3621
            .ahead,
3622
        Some(0)
3623
    );
3624
    // A second workspace inherits the current bookmark and can switch independently.
3625
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
3626
    assert_eq!(ws.config.bookmark, "main");
3627
    let mut ws = ws;
3628
    ws.bookmark_switch("feature", false).unwrap();
3629
    assert_eq!(
3630
        Repo::open(&r).unwrap().config.bookmark,
3631
        "main",
3632
        "the first workspace is unaffected"
3633
    );
3634
    assert!(
3635
        repo.bookmark_delete("feature").is_err(),
3636
        "current bookmark of another workspace"
3637
    );
3638
    ws.bookmark_switch("main", false).unwrap();
3639
    // Set and delete.
3640
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
3641
    assert!(repo.bookmark_delete("main").is_err(), "current here");
3642
    repo.bookmark_delete("feature").unwrap();
3643
    assert!(repo.resolve_heads("feature").is_err());
3644
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
3645
    assert!(
3646
        repo.checkout(&[h_a], false, "checkout").is_ok(),
3647
        "changes of a deleted bookmark remain"
3648
    );
3649
}
3650
3651
#[test]
3652
fn oxygen_subrepos_pin_follow_and_update() {
3653
    hermetic();
3654
    let dir = tempfile::tempdir().unwrap();
3655
    let root = dir.path();
3656
    // A library repository with two commits, and a bare-ish origin for it.
3657
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
3658
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
3659
    let lib = Repo::clone(&lib_url, &root.join("lib"))
3660
        .unwrap()
3661
        .with_home(root.join("home"));
3662
    write(&root.join("lib"), "lib.txt", b"v1\n");
3663
    let l1 = lib.commit("lib v1", &[]).unwrap();
3664
    assert!(lib.push("origin", false).unwrap()[0].ok);
3665
    let _ = lib_origin;
3666
3667
    // The application (a clone of its own origin) adds it as a subrepo.
3668
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
3669
    let app_url = root.join("app-origin").to_string_lossy().to_string();
3670
    let _ = app_origin;
3671
    let app_dir = root.join("app");
3672
    let app = Repo::clone(&app_url, &app_dir)
3673
        .unwrap()
3674
        .with_home(root.join("home"));
3675
    write(&app_dir, "main.txt", b"app\n");
3676
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
3677
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
3678
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
3679
    let snap = app.snapshot("status").unwrap();
3680
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3681
    assert_eq!(
3682
        paths,
3683
        vec![".oxymodules", "libs/lib", "main.txt"],
3684
        "the nested files are not walked"
3685
    );
3686
    let a1 = app.commit("app with lib", &[]).unwrap();
3687
    let files = app.load_state(&[a1]).unwrap().materialize().files;
3688
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
3689
    assert!(!files.contains_key("libs/lib/lib.txt"));
3690
    assert!(!app.snapshot("status").unwrap().changed);
3691
    let subs = app.subrepos().unwrap();
3692
    assert_eq!(subs.len(), 1);
3693
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
3694
3695
    // Advance the nested repository: the parent sees a modified pin.
3696
    let nested = Repo::open(&app_dir.join("libs/lib"))
3697
        .unwrap()
3698
        .with_home(root.join("home"));
3699
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
3700
    let l2 = nested.commit("lib v2", &[]).unwrap();
3701
    assert!(nested.push("origin", false).unwrap()[0].ok);
3702
    let snap = app.snapshot("status").unwrap();
3703
    assert_eq!(
3704
        snap.statuses
3705
            .iter()
3706
            .map(|s| (s.path.as_str(), s.status))
3707
            .collect::<Vec<_>>(),
3708
        vec![("libs/lib", ChangeStatus::Modified)]
3709
    );
3710
    let a2 = app.commit("bump lib", &[]).unwrap();
3711
    // Checking out the older app state brings the nested working copy back
3712
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
3713
    let r = app.checkout(&[a1], false, "checkout").unwrap();
3714
    assert!(
3715
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
3716
        "{:?}",
3717
        r.notes
3718
    );
3719
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3720
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
3721
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
3722
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
3723
    assert!(!app.snapshot("status").unwrap().changed);
3724
    // A dirty nested repository is left alone and reported.
3725
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
3726
    let r = app.checkout(&[a2], false, "checkout").unwrap();
3727
    assert!(
3728
        r.notes.iter().any(|n| n.contains("uncommitted")),
3729
        "{:?}",
3730
        r.notes
3731
    );
3732
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3733
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
3734
    let r = app.submodule_update(false, &[]).unwrap();
3735
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
3736
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
3737
    let _ = l2;
3738
3739
    // A fresh clone of the app has the pin but no nested repository until update --init.
3740
    assert!(app.push("origin", false).unwrap()[0].ok);
3741
    let clone_dir = root.join("app-clone");
3742
    let clone = Repo::clone(&app_url, &clone_dir)
3743
        .unwrap()
3744
        .with_home(root.join("home"));
3745
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
3746
    assert_eq!(
3747
        clone.submodule_update(false, &[]).unwrap(),
3748
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
3749
    );
3750
    assert_eq!(
3751
        clone.submodule_update(true, &[]).unwrap(),
3752
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
3753
    );
3754
    assert_eq!(
3755
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
3756
        b"v2\n"
3757
    );
3758
    assert!(!clone.snapshot("status").unwrap().changed);
3759
    // Removing the subrepo leaves the directory and drops the node.
3760
    clone.submodule_remove("libs/lib").unwrap();
3761
    let snap = clone.snapshot("status").unwrap();
3762
    assert!(
3763
        snap.statuses
3764
            .iter()
3765
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
3766
        "{:?}",
3767
        snap.statuses
3768
    );
3769
    let c = clone.commit("drop lib", &[]).unwrap();
3770
    assert!(!clone
3771
        .load_state(&[c])
3772
        .unwrap()
3773
        .materialize()
3774
        .files
3775
        .contains_key("libs/lib"));
3776
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
3777
    assert!(
3778
        !clone.snapshot("status").unwrap().changed,
3779
        "an unregistered nested repository is ignored"
3780
    );
3781
}
3782
3783
#[test]
3784
fn git_submodules_import_and_export_as_gitlinks() {
3785
    hermetic();
3786
    if std::process::Command::new("git")
3787
        .arg("--version")
3788
        .output()
3789
        .is_err()
3790
    {
3791
        eprintln!("git not installed; skipping");
3792
        return;
3793
    }
3794
    let dir = tempfile::tempdir().unwrap();
3795
    let root = dir.path();
3796
    let git_in = |d: &Path, args: &[&str]| -> String {
3797
        let out = std::process::Command::new("git")
3798
            .arg("-C")
3799
            .arg(d)
3800
            .args([
3801
                "-c",
3802
                "user.name=Grace",
3803
                "-c",
3804
                "[email protected]",
3805
                "-c",
3806
                "commit.gpgsign=false",
3807
                "-c",
3808
                "protocol.file.allow=always",
3809
            ])
3810
            .args(args)
3811
            .output()
3812
            .unwrap();
3813
        assert!(
3814
            out.status.success(),
3815
            "git {args:?}: {}",
3816
            String::from_utf8_lossy(&out.stderr)
3817
        );
3818
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3819
    };
3820
    let sub = root.join("sub");
3821
    fs::create_dir_all(&sub).unwrap();
3822
    git_in(&sub, &["init", "-q", "-b", "main"]);
3823
    write(&sub, "s.txt", b"sub\n");
3824
    git_in(&sub, &["add", "."]);
3825
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
3826
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
3827
    let g = root.join("main.git");
3828
    fs::create_dir_all(&g).unwrap();
3829
    git_in(&g, &["init", "-q", "-b", "main"]);
3830
    write(&g, "README.md", b"# app\n");
3831
    git_in(&g, &["add", "."]);
3832
    git_in(&g, &["commit", "-q", "-m", "initial"]);
3833
    git_in(
3834
        &g,
3835
        &[
3836
            "submodule",
3837
            "add",
3838
            "-q",
3839
            sub.to_str().unwrap(),
3840
            "vendor/sub",
3841
        ],
3842
    );
3843
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
3844
3845
    let dest = root.join("oxy");
3846
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3847
    let rep = repo.import_git(&g, "main").unwrap();
3848
    assert_eq!((rep.commits, rep.submodules), (2, 1));
3849
    let files = repo
3850
        .load_state(&repo.bookmark_heads().unwrap())
3851
        .unwrap()
3852
        .materialize()
3853
        .files;
3854
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
3855
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
3856
        panic!()
3857
    };
3858
    assert_eq!(
3859
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
3860
        crate::subrepo::Pin::Git {
3861
            sha: sub_sha.clone(),
3862
            branch: "HEAD".into()
3863
        }
3864
    );
3865
    let modules =
3866
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
3867
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
3868
    assert!(modules.entries["vendor/sub"].git);
3869
    assert!(
3870
        files.contains_key(".gitmodules"),
3871
        "the Git file is kept for round trips"
3872
    );
3873
    assert!(
3874
        !dest.join("vendor/sub/.git").exists(),
3875
        "not cloned until update --init"
3876
    );
3877
    assert!(!repo.snapshot("status").unwrap().changed);
3878
    // update --init clones it at the pinned commit; status is unchanged.
3879
    assert_eq!(
3880
        repo.submodule_update(true, &[]).unwrap(),
3881
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
3882
    );
3883
    assert_eq!(
3884
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
3885
        sub_sha
3886
    );
3887
    assert!(!repo.snapshot("status").unwrap().changed);
3888
    // Export writes the gitlink and .gitmodules back.
3889
    let mirror = root.join("mirror.git");
3890
    let rep = repo.git_export(&mirror).unwrap();
3891
    assert_eq!(rep.skipped_subrepos, 0);
3892
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
3893
    assert!(
3894
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
3895
        "{ls}"
3896
    );
3897
    assert_eq!(
3898
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
3899
        ".gitmodules\nREADME.md\nvendor"
3900
    );
3901
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
3902
    assert_eq!(
3903
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
3904
        orig_tree,
3905
        "tree round trip"
3906
    );
3907
}
3908
3909
#[test]
3910
fn partial_commits_by_path_and_by_hunk() {
3911
    hermetic();
3912
    let dir = tempfile::tempdir().unwrap();
3913
    let root = dir.path();
3914
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3915
    write(root, "a.txt", b"1\n2\n3\n");
3916
    write(root, "b.txt", b"b\n");
3917
    let h0 = repo.commit("base", &[]).unwrap();
3918
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
3919
    write(root, "b.txt", b"b\nbb\n");
3920
    write(root, "c.txt", b"c\n");
3921
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
3922
    let h1 = repo
3923
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
3924
        .unwrap();
3925
    let c1 = repo.store().get_change(&h1).unwrap();
3926
    assert!(
3927
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
3928
        "{:?}",
3929
        c1.tree_ops
3930
    );
3931
    assert_eq!(c1.deps, vec![h0]);
3932
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
3933
    assert!(
3934
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
3935
    );
3936
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
3937
    assert!(!files.contains_key("c.txt"));
3938
    let snap = repo.snapshot("status").unwrap();
3939
    assert_eq!(
3940
        snap.statuses
3941
            .iter()
3942
            .map(|s| (s.path.as_str(), s.status))
3943
            .collect::<Vec<_>>(),
3944
        vec![
3945
            ("b.txt", ChangeStatus::Modified),
3946
            ("c.txt", ChangeStatus::Added)
3947
        ]
3948
    );
3949
    assert_eq!(
3950
        fs::read(root.join("b.txt")).unwrap(),
3951
        b"b\nbb\n",
3952
        "disk untouched"
3953
    );
3954
    // By hunk: pick the b.txt insert; c.txt's addition is left.
3955
    let (_, hunks) = repo.hunks().unwrap();
3956
    let b_hunk = hunks
3957
        .iter()
3958
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
3959
        .unwrap()
3960
        .index;
3961
    let h2 = repo
3962
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
3963
        .unwrap();
3964
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3965
    assert!(
3966
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
3967
    );
3968
    assert!(!files.contains_key("c.txt"));
3969
    let snap = repo.snapshot("status").unwrap();
3970
    assert_eq!(
3971
        snap.statuses
3972
            .iter()
3973
            .map(|s| s.path.as_str())
3974
            .collect::<Vec<_>>(),
3975
        vec!["c.txt"]
3976
    );
3977
    // Choosing only the content hunk of a file in a new directory pulls in
3978
    // the directory and file additions it needs.
3979
    write(root, "d/e.txt", b"e\n");
3980
    let (_, hunks) = repo.hunks().unwrap();
3981
    let e_insert = hunks
3982
        .iter()
3983
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
3984
        .unwrap()
3985
        .index;
3986
    let h3 = repo
3987
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
3988
        .unwrap();
3989
    let c3 = repo.store().get_change(&h3).unwrap();
3990
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
3991
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
3992
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
3993
    // Choosing a new file's addition hunk brings its content along.
3994
    write(root, "f/g.txt", b"g\n");
3995
    let (_, hunks) = repo.hunks().unwrap();
3996
    let g_add = hunks
3997
        .iter()
3998
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
3999
        .unwrap()
4000
        .index;
4001
    let h4 = repo
4002
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
4003
        .unwrap();
4004
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
4005
    assert!(
4006
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
4007
    );
4008
    assert!(!repo
4009
        .snapshot("status")
4010
        .unwrap()
4011
        .statuses
4012
        .iter()
4013
        .any(|s| s.path == "f/g.txt"));
4014
    // Everything left commits normally; the working copy is then clean.
4015
    repo.commit("the rest", &[]).unwrap();
4016
    assert!(!repo.snapshot("status").unwrap().changed);
4017
    let files = repo
4018
        .load_state(&repo.bookmark_heads().unwrap())
4019
        .unwrap()
4020
        .materialize()
4021
        .files;
4022
    assert!(files.contains_key("c.txt"));
4023
}
4024
4025
#[test]
4026
fn blame_attributes_lines_to_introducing_changes_across_renames() {
4027
    hermetic();
4028
    let dir = tempfile::tempdir().unwrap();
4029
    let root = dir.path();
4030
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
4031
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
4032
        .unwrap();
4033
    write(root, "a.txt", b"one\n");
4034
    let h1 = repo.commit("first", &[]).unwrap();
4035
    write(root, "a.txt", b"one\ntwo\n");
4036
    let h2 = repo.commit("second", &[]).unwrap();
4037
    let b = repo.blame("a.txt").unwrap();
4038
    assert_eq!(
4039
        b.iter()
4040
            .map(|l| (l.line, l.hash, l.text.as_slice()))
4041
            .collect::<Vec<_>>(),
4042
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
4043
    );
4044
    assert!(b.iter().all(|l| l.author == "Ada"));
4045
    assert_eq!(
4046
        b[0].change_id,
4047
        repo.store().get_change(&h1).unwrap().change_id
4048
    );
4049
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
4050
    repo.commit("rename", &[]).unwrap();
4051
    let b = repo.blame("b.txt").unwrap();
4052
    assert_eq!(
4053
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
4054
        vec![h1, h2],
4055
        "the node survives the rename"
4056
    );
4057
    assert!(repo.blame("a.txt").is_err());
4058
}
4059
4060
#[test]
4061
fn bisect_finds_the_first_bad_change() {
4062
    hermetic();
4063
    let dir = tempfile::tempdir().unwrap();
4064
    let root = dir.path();
4065
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4066
    let mut content = String::new();
4067
    let mut hashes = Vec::new();
4068
    for i in 1..=8 {
4069
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
4070
        write(root, "f.txt", content.as_bytes());
4071
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
4072
    }
4073
    // Each step appends after the previous line, so the chain is linear.
4074
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
4075
    repo.bisect_start().unwrap();
4076
    assert!(matches!(
4077
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
4078
        BisectStep::NeedMarks { good: 1, bad: 0 }
4079
    ));
4080
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4081
    assert!(
4082
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
4083
        "{step:?}"
4084
    );
4085
    // Automated: bad when the bug line is present.
4086
    let step = repo
4087
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
4088
        .unwrap();
4089
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4090
    assert_eq!(
4091
        repo.bisect_status().unwrap(),
4092
        Some(BisectStep::Found { culprit: hashes[4] })
4093
    );
4094
    repo.bisect_reset().unwrap();
4095
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
4096
    assert!(repo.bisect_status().unwrap().is_none());
4097
    assert!(!repo.snapshot("status").unwrap().changed);
4098
    // Manual marks and a skip.
4099
    repo.bisect_start().unwrap();
4100
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4101
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4102
    let mut skipped_once = false;
4103
    let mut guard = 0;
4104
    while let BisectStep::Testing { .. } = step {
4105
        guard += 1;
4106
        assert!(guard < 20);
4107
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4108
        if !skipped_once && text.contains("line 6") {
4109
            // An untestable state away from the boundary: the search routes around it.
4110
            skipped_once = true;
4111
            step = repo.bisect_mark(None, &[]).unwrap();
4112
            continue;
4113
        }
4114
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
4115
    }
4116
    assert!(skipped_once);
4117
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4118
    repo.bisect_reset().unwrap();
4119
    // Skipping the culprit itself leaves it among the candidates reported.
4120
    repo.bisect_start().unwrap();
4121
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4122
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4123
    let mut guard = 0;
4124
    while let BisectStep::Testing { heads, .. } = &step {
4125
        guard += 1;
4126
        assert!(guard < 20);
4127
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4128
        let is_culprit_state =
4129
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
4130
        step = if is_culprit_state {
4131
            repo.bisect_mark(None, &[]).unwrap()
4132
        } else {
4133
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
4134
        };
4135
    }
4136
    match step {
4137
        BisectStep::Inconclusive { candidates } => assert!(
4138
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
4139
            "{candidates:?}"
4140
        ),
4141
        other => panic!("{other:?}"),
4142
    }
4143
    repo.bisect_reset().unwrap();
4144
}
4145
4146
#[test]
4147
fn squash_folds_a_change_into_its_dependency() {
4148
    hermetic();
4149
    let dir = tempfile::tempdir().unwrap();
4150
    let root = dir.path();
4151
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4152
    write(root, "a.txt", b"1\n");
4153
    let a = repo.commit("A", &[]).unwrap();
4154
    write(root, "a.txt", b"1\n2\n");
4155
    let c = repo.commit("C", &[]).unwrap();
4156
    write(root, "a.txt", b"1\n2\n3\n");
4157
    let e = repo.commit("E", &[]).unwrap();
4158
    write(root, "b.txt", b"b\n");
4159
    let b = repo.commit("B", &[]).unwrap();
4160
    let id_a = repo.store().get_change(&a).unwrap().change_id;
4161
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4162
    // E depends on C which A lacks: refused, naming it.
4163
    let err = repo.squash(&e, &a).unwrap_err().to_string();
4164
    assert!(err.contains(&c.short(12)), "{err}");
4165
    // C into A: A' has both, C is gone, E follows and still reads the same.
4166
    let a2 = repo.squash(&c, &a).unwrap();
4167
    let a2c = repo.store().get_change(&a2).unwrap();
4168
    assert_eq!(a2c.change_id, id_a);
4169
    assert!(a2c.deps.is_empty());
4170
    let heads = repo.bookmark_heads().unwrap();
4171
    let st = repo.load_state(&heads).unwrap();
4172
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
4173
    let e2 = st
4174
        .changes()
4175
        .find(|(_, m)| m.change_id == id_e)
4176
        .map(|(h, _)| *h)
4177
        .unwrap();
4178
    assert_eq!(
4179
        repo.store().get_change(&e2).unwrap().deps,
4180
        vec![a2],
4181
        "E now depends on A' alone"
4182
    );
4183
    let files = st.materialize().files;
4184
    assert!(
4185
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
4186
    );
4187
    assert!(files.contains_key("b.txt"));
4188
    assert!(st.contains(&b));
4189
    assert!(!repo.snapshot("status").unwrap().changed);
4190
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
4191
    // Undo restores the three original changes.
4192
    repo.undo().unwrap();
4193
    repo.undo().unwrap();
4194
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
4195
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
4196
}
4197
4198
#[test]
4199
fn rebase_re_expresses_a_change_against_another_base() {
4200
    hermetic();
4201
    let dir = tempfile::tempdir().unwrap();
4202
    let root = dir.path();
4203
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4204
    write(root, "a.txt", b"1\n2\n");
4205
    let a = repo.commit("A", &[]).unwrap();
4206
    write(root, "a.txt", b"1\n2\n3\n");
4207
    let c = repo.commit("C: append 3", &[]).unwrap();
4208
    write(root, "a.txt", b"1\n2\n3\n4\n");
4209
    let e = repo.commit("E: append 4", &[]).unwrap();
4210
    // A different base: A plus a change that prepends a line.
4211
    repo.checkout(&[a], true, "checkout").unwrap();
4212
    write(root, "a.txt", b"0\n1\n2\n");
4213
    let d = repo.commit("D: prepend 0", &[]).unwrap();
4214
    let id_c = repo.store().get_change(&c).unwrap().change_id;
4215
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4216
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
4217
    let c2 = repo.rebase(&c, &[d]).unwrap();
4218
    let c2c = repo.store().get_change(&c2).unwrap();
4219
    assert_eq!(c2c.change_id, id_c);
4220
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
4221
    let heads = repo.bookmark_heads().unwrap();
4222
    let st = repo.load_state(&heads).unwrap();
4223
    assert!(!st.contains(&c) && st.contains(&d));
4224
    let e2 = st
4225
        .changes()
4226
        .find(|(_, m)| m.change_id == id_e)
4227
        .map(|(h, _)| *h)
4228
        .unwrap();
4229
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
4230
    assert!(
4231
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
4232
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
4233
    );
4234
    let files = st.materialize().files;
4235
    assert!(
4236
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
4237
        "{:?}",
4238
        files["a.txt"].content
4239
    );
4240
    assert!(!files["a.txt"].is_conflicted());
4241
    // Rebasing onto a state that already contains the change is refused.
4242
    assert!(repo.rebase(&c2, &[c2]).is_err());
4243
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
4244
    assert!(
4245
        err.contains("lacks dependencies"),
4246
        "E needs C, which D's state does not have: {err}"
4247
    );
4248
}
4249
4250
#[test]
4251
fn unsigned_tags_keep_their_message() {
4252
    hermetic();
4253
    let dir = tempfile::tempdir().unwrap();
4254
    let root = dir.path();
4255
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4256
    write(root, "a.txt", b"a\n");
4257
    repo.commit("a", &[]).unwrap();
4258
    assert!(repo.secret_key().unwrap().is_none());
4259
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
4260
        .unwrap();
4261
    let tags = repo.tags().unwrap();
4262
    assert_eq!(
4263
        (
4264
            tags[0].name.as_str(),
4265
            tags[0].message.as_str(),
4266
            tags[0].signer.as_deref()
4267
        ),
4268
        ("v1", "first release", None)
4269
    );
4270
    assert!(
4271
        repo.tag_refs().unwrap()[0].attestation.is_none(),
4272
        "an unsigned attestation is not advertised"
4273
    );
4274
}
4275
4276
#[test]
4277
fn fsck_passes_a_sound_repository_and_names_each_fault() {
4278
    // Files on disk are what this tests: tampering with them, and the
4279
    // directory store's crash points.
4280
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4281
        return;
4282
    }
4283
    hermetic();
4284
    let dir = tempfile::tempdir().unwrap();
4285
    let root = dir.path();
4286
    let origin_path = root.join("origin");
4287
    let origin = Repo::init(&origin_path).unwrap();
4288
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
4289
        .unwrap()
4290
        .with_home(root.join("home-a"));
4291
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4292
        .unwrap();
4293
    write(&root.join("a"), "f.txt", b"one\n");
4294
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
4295
    let h1 = a.commit("first", &[]).unwrap();
4296
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
4297
    let h2 = a.commit("second", &[]).unwrap();
4298
    a.tag_create("v1", &[h2], "first release").unwrap();
4299
    a.checkpoint().unwrap();
4300
    assert!(a.push("origin", false).unwrap()[0].ok);
4301
4302
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
4303
    for repo in [&a, &origin] {
4304
        let rep = repo.fsck().unwrap();
4305
        assert_eq!(rep.problems, vec![], "{rep:?}");
4306
        // The two commits, plus the working copy's change in `a`.
4307
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
4308
        assert!(rep.ops > 1 && rep.objects > 5);
4309
    }
4310
    assert!(origin.fsck().unwrap().attestations >= 1);
4311
4312
    // A flipped byte in a stored object is corruption, named by hash.
4313
    let c1 = a.store().path_for(&h1);
4314
    let pristine = fs::read(&c1).unwrap();
4315
    let mut bytes = pristine.clone();
4316
    *bytes.last_mut().unwrap() ^= 1;
4317
    fs::write(&c1, &bytes).unwrap();
4318
    let rep = a.fsck().unwrap();
4319
    assert!(rep.errors() >= 1);
4320
    assert!(
4321
        rep.problems
4322
            .iter()
4323
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
4324
        "{rep:?}"
4325
    );
4326
    fs::write(&c1, &pristine).unwrap();
4327
    assert_eq!(a.fsck().unwrap().errors(), 0);
4328
4329
    // A missing change is named with what needed it.
4330
    fs::remove_file(&c1).unwrap();
4331
    let rep = a.fsck().unwrap();
4332
    assert!(
4333
        rep.problems.iter().any(|p| p.severity == Severity::Error
4334
            && p.object == Some(h1)
4335
            && p.what.contains("change missing, needed by change")),
4336
        "{rep:?}"
4337
    );
4338
    fs::write(&c1, &pristine).unwrap();
4339
4340
    // A missing blob is an error in a full clone.
4341
    let c2 = a.store().get_change(&h1).unwrap();
4342
    let blob = c2
4343
        .edits
4344
        .iter()
4345
        .find_map(|e| match e {
4346
            Edit::Replace { new: Some(b), .. } => Some(*b),
4347
            _ => None,
4348
        })
4349
        .expect("the binary file is a blob");
4350
    let bp = a.store().path_for(&blob);
4351
    let blob_bytes = fs::read(&bp).unwrap();
4352
    fs::remove_file(&bp).unwrap();
4353
    let rep = a.fsck().unwrap();
4354
    assert!(
4355
        rep.problems
4356
            .iter()
4357
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
4358
        "{rep:?}"
4359
    );
4360
    fs::write(&bp, &blob_bytes).unwrap();
4361
4362
    // A broken op log head is reported, not a crash.
4363
    let head = root.join("a/.oxy/ops/head");
4364
    let saved = fs::read(&head).unwrap();
4365
    fs::write(&head, b"not a hash").unwrap();
4366
    let rep = a.fsck().unwrap();
4367
    assert!(
4368
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
4369
        "{rep:?}"
4370
    );
4371
    fs::write(&head, saved).unwrap();
4372
    assert_eq!(a.fsck().unwrap().problems, vec![]);
4373
}
4374
4375
/// Copy a directory tree (for restoring a pristine repository).
4376
fn copy_tree(from: &Path, to: &Path) {
4377
    fs::create_dir_all(to).unwrap();
4378
    for e in fs::read_dir(from).unwrap() {
4379
        let e = e.unwrap();
4380
        let target = to.join(e.file_name());
4381
        if e.file_type().unwrap().is_dir() {
4382
            copy_tree(&e.path(), &target);
4383
        } else {
4384
            fs::copy(e.path(), &target).unwrap();
4385
        }
4386
    }
4387
}
4388
4389
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
4390
/// would, and check that both repositories still open, pass `fsck`, and
4391
/// accept the same operation again.
4392
#[test]
4393
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
4394
    // Files on disk are what this tests: tampering with them, and the
4395
    // directory store's crash points.
4396
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4397
        return;
4398
    }
4399
    use crate::durable::failpoint;
4400
    hermetic();
4401
    let dir = tempfile::tempdir().unwrap();
4402
    let pristine = dir.path().join("pristine");
4403
    let origin_path = pristine.join("origin");
4404
    Repo::init(&origin_path).unwrap();
4405
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
4406
        .unwrap()
4407
        .with_home(dir.path().join("home"));
4408
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4409
        .unwrap();
4410
    write(&pristine.join("a"), "f.txt", b"one\n");
4411
    a.commit("first", &[]).unwrap();
4412
    assert!(a.push("origin", false).unwrap()[0].ok);
4413
    drop(a);
4414
4415
    type Op = fn(&Repo) -> Result<()>;
4416
    let edit_and_commit: Op = |r| {
4417
        write(r.root(), "f.txt", b"one\ntwo\n");
4418
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
4419
        r.commit("second", &[]).map(|_| ())
4420
    };
4421
    let push: Op = |r| {
4422
        let res = r.push("origin", false)?;
4423
        if res.iter().all(|x| x.ok) {
4424
            Ok(())
4425
        } else {
4426
            Err(RepoError::Msg(format!("{res:?}")))
4427
        }
4428
    };
4429
4430
    for (name, prepare, op) in [
4431
        ("commit", None, edit_and_commit),
4432
        ("push", Some(edit_and_commit), push),
4433
    ] {
4434
        let mut steps = 0;
4435
        for n in 1.. {
4436
            let run = dir.path().join(format!("{name}-{n}"));
4437
            copy_tree(&pristine, &run);
4438
            // Clones record their remote by path; point it at this copy.
4439
            let open = |p: &Path| {
4440
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
4441
                r.config
4442
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
4443
                    .unwrap();
4444
                r.save_config().unwrap();
4445
                r
4446
            };
4447
            let a = open(&run.join("a"));
4448
            if let Some(prep) = prepare {
4449
                prep(&a).unwrap();
4450
            }
4451
            failpoint::crash_after(n);
4452
            let outcome = op(&a);
4453
            let crashed = failpoint::disarm();
4454
            drop(a);
4455
            if !crashed {
4456
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
4457
                steps = n - 1;
4458
                break;
4459
            }
4460
            assert!(
4461
                outcome.is_err(),
4462
                "{name}: a crash at step {n} was swallowed"
4463
            );
4464
            for repo in ["a", "origin"] {
4465
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
4466
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
4467
                });
4468
                let rep = r.fsck().unwrap();
4469
                assert_eq!(
4470
                    rep.errors(),
4471
                    0,
4472
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
4473
                    rep.problems
4474
                );
4475
            }
4476
            // The interrupted operation can simply be run again.
4477
            let a = open(&run.join("a"));
4478
            // A crash after the commit point leaves the commit done.
4479
            let landed = a
4480
                .bookmark_heads()
4481
                .unwrap()
4482
                .iter()
4483
                .any(|h| a.store().get_change(h).unwrap().message == "second");
4484
            let again = match (name, landed) {
4485
                ("commit", true) => Ok(()),
4486
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
4487
                _ => op(&a),
4488
            };
4489
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
4490
            assert_eq!(a.fsck().unwrap().errors(), 0);
4491
            fs::remove_dir_all(&run).unwrap();
4492
        }
4493
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
4494
    }
4495
}
4496
4497
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
4498
/// running at the same time lose nothing: every commit ends up on the
4499
/// bookmark, locally and on the remote, and the repository passes fsck.
4500
#[test]
4501
fn concurrent_commits_in_two_workspaces_lose_nothing() {
4502
    hermetic();
4503
    let dir = tempfile::tempdir().unwrap();
4504
    let root = dir.path();
4505
    let origin = root.join("origin");
4506
    Repo::init_bare_unbound(&origin).unwrap();
4507
    let main = root.join("main");
4508
    let mut repo = Repo::init(&main).unwrap();
4509
    repo.config
4510
        .set("remote.origin.url", &origin.to_string_lossy())
4511
        .unwrap();
4512
    repo.save_config().unwrap();
4513
    write(&main, "seed.txt", b"seed\n");
4514
    repo.commit("seed", &[]).unwrap();
4515
    let second = root.join("second");
4516
    repo.workspace_add(&second, None).unwrap();
4517
    drop(repo);
4518
4519
    const EACH: usize = 15;
4520
    std::thread::scope(|s| {
4521
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
4522
            s.spawn(move || {
4523
                let r = Repo::open(&dir).unwrap();
4524
                for i in 0..EACH {
4525
                    write(
4526
                        &dir,
4527
                        &format!("{tag}-{i}.txt"),
4528
                        format!("{tag} {i}\n").as_bytes(),
4529
                    );
4530
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
4531
                    if push && i % 5 == 4 {
4532
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
4533
                        let _ = r.push("origin", false);
4534
                    }
4535
                }
4536
            });
4537
        }
4538
    });
4539
4540
    let repo = Repo::open(&main).unwrap();
4541
    let heads = repo.bookmark_heads().unwrap();
4542
    let state = repo.load_state(&heads).unwrap();
4543
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
4544
    for tag in ["a", "b"] {
4545
        for i in 0..EACH {
4546
            assert!(
4547
                messages.contains(&format!("{tag} {i}")),
4548
                "lost commit {tag} {i}; have {messages:?}"
4549
            );
4550
        }
4551
    }
4552
    let rep = repo.fsck().unwrap();
4553
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
4554
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
4555
    let hosted = Repo::open(&origin).unwrap();
4556
    let hosted_heads = hosted.bookmark_heads().unwrap();
4557
    assert_eq!(
4558
        hosted.load_state(&hosted_heads).unwrap().len(),
4559
        state.len(),
4560
        "the remote has every commit"
4561
    );
4562
}
4563
4564
/// Two operations recorded from the same parent (what two processes do
4565
/// when they race) are merged: both bookmarks' heads survive, and a
4566
/// change made on one side only is kept.
4567
#[test]
4568
fn operations_from_the_same_parent_are_merged() {
4569
    hermetic();
4570
    let dir = tempfile::tempdir().unwrap();
4571
    let root = dir.path();
4572
    let repo = Repo::init(root).unwrap();
4573
    write(root, "a.txt", b"a\n");
4574
    let a = repo.commit("a", &[]).unwrap();
4575
    write(root, "b.txt", b"b\n");
4576
    let b = repo.commit("b", &[]).unwrap();
4577
    let (x, op) = repo.head_op().unwrap();
4578
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
4579
4580
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
4581
    let mut one = op.view.clone();
4582
    one.bookmarks.insert("main".into(), state(vec![a]));
4583
    one.bookmarks.insert("topic".into(), state(vec![a]));
4584
    let mut two = op.view.clone();
4585
    two.bookmarks.insert("main".into(), state(vec![b]));
4586
    repo.record_op(&[x], "one", one).unwrap();
4587
    let merged = repo.record_op(&[x], "two", two).unwrap();
4588
4589
    let (head, op) = repo.head_op().unwrap();
4590
    assert_eq!(head, merged);
4591
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
4592
    assert!(op.command.contains("merged with a concurrent operation"));
4593
    let mut main = repo
4594
        .store()
4595
        .get_state(&op.view.bookmarks["main"])
4596
        .unwrap()
4597
        .heads;
4598
    main.sort();
4599
    let mut want = vec![a, b];
4600
    want.sort();
4601
    assert_eq!(main, want, "both sides' heads are kept");
4602
    assert!(
4603
        op.view.bookmarks.contains_key("topic"),
4604
        "a one-sided change survives"
4605
    );
4606
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4607
}
4608
4609
#[test]
4610
fn failed_requests_come_with_a_next_step() {
4611
    use crate::protocol::hint_for;
4612
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
4613
        .unwrap()
4614
        .contains("token"));
4615
    assert!(hint_for("…: HTTP 403: forbidden")
4616
        .unwrap()
4617
        .contains("repo:write"));
4618
    assert!(hint_for("…: HTTP 404: no such repository")
4619
        .unwrap()
4620
        .contains("owner and repository name"));
4621
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
4622
        .unwrap()
4623
        .contains("oxyhub-ca.pem"));
4624
    assert!(hint_for("Connect error: Connection refused (os error 111)")
4625
        .unwrap()
4626
        .contains("running"));
4627
    assert!(hint_for("Dns Failed: failed to lookup address information")
4628
        .unwrap()
4629
        .contains("resolve"));
4630
    assert_eq!(hint_for("something else entirely"), None);
4631
}
4632
4633
#[test]
4634
fn doctor_names_problems_and_what_to_do() {
4635
    hermetic();
4636
    let dir = tempfile::tempdir().unwrap();
4637
    let root = dir.path();
4638
    let origin = root.join("origin");
4639
    Repo::init_bare_unbound(&origin).unwrap();
4640
    let mut repo = Repo::init(&root.join("r"))
4641
        .unwrap()
4642
        .with_home(root.join("home"));
4643
    let find = |r: &DoctorReport, area: &str, h: Health| {
4644
        r.checks
4645
            .iter()
4646
            .find(|c| c.area == area && c.health == h)
4647
            .cloned()
4648
    };
4649
4650
    let r = repo.doctor(true);
4651
    assert!(find(&r, "identity", Health::Warn)
4652
        .unwrap()
4653
        .hint
4654
        .unwrap()
4655
        .contains("oxy identity create"));
4656
    assert!(find(&r, "repository", Health::Ok).is_some());
4657
4658
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4659
        .unwrap();
4660
    repo.config.set("author.name", "Ada").unwrap();
4661
    repo.config.set("author.email", "[email protected]").unwrap();
4662
    repo.config
4663
        .set("remote.origin.url", &origin.to_string_lossy())
4664
        .unwrap();
4665
    repo.config
4666
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
4667
        .unwrap();
4668
    repo.config.set("remote.down.token", "t").unwrap();
4669
    repo.config
4670
        .set("remote.badca.url", "https://example.invalid/a/b")
4671
        .unwrap();
4672
    repo.config
4673
        .set(
4674
            "remote.badca.ca",
4675
            &root.join("missing.pem").to_string_lossy(),
4676
        )
4677
        .unwrap();
4678
    repo.save_config().unwrap();
4679
4680
    let r = repo.doctor(true);
4681
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
4682
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
4683
    assert!(find(&r, "remote origin", Health::Ok)
4684
        .unwrap()
4685
        .message
4686
        .contains("first push binds it"));
4687
    let down = find(&r, "remote down", Health::Fail).unwrap();
4688
    assert!(
4689
        down.hint.as_deref().unwrap_or("").contains("running"),
4690
        "{down:?}"
4691
    );
4692
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
4693
    assert!(
4694
        badca.hint.unwrap().contains("remote.badca.ca"),
4695
        "the remote's own name is in the hint"
4696
    );
4697
    assert_eq!(r.worst(), Health::Fail);
4698
4699
    // Offline, nothing is contacted.
4700
    let r = repo.doctor(false);
4701
    assert!(find(&r, "remote down", Health::Fail).is_none());
4702
    assert!(find(&r, "remote down", Health::Ok)
4703
        .unwrap()
4704
        .message
4705
        .contains("not contacted"));
4706
}
4707
4708
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
4709
/// after it. Inserting after `b` and then deleting `b`, one commit after
4710
/// the other, must not leave a delete/insert conflict.
4711
#[test]
4712
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
4713
    hermetic();
4714
    let dir = tempfile::tempdir().unwrap();
4715
    let root = dir.path();
4716
    let repo = Repo::init(root).unwrap();
4717
    write(root, "f", b"a\nb\nc\n");
4718
    repo.commit("base", &[]).unwrap();
4719
    write(root, "f", b"a\nb\nx\nc\n");
4720
    let insert = repo.commit("insert x after b", &[]).unwrap();
4721
    write(root, "f", b"a\nx\nc\n");
4722
    let delete = repo.commit("delete b", &[]).unwrap();
4723
    assert!(
4724
        repo.store()
4725
            .get_change(&delete)
4726
            .unwrap()
4727
            .deps
4728
            .contains(&insert),
4729
        "the deletion depends on the insertion below the deleted line"
4730
    );
4731
    let heads = repo.bookmark_heads().unwrap();
4732
    assert_eq!(heads, vec![delete]);
4733
    let snap = repo.load_state(&heads).unwrap().materialize();
4734
    assert!(!snap.is_conflicted());
4735
    assert!(
4736
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
4737
    );
4738
}
4739
4740
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
4741
/// replacement depends on the change that set the blob it replaces.
4742
#[test]
4743
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
4744
    hermetic();
4745
    let dir = tempfile::tempdir().unwrap();
4746
    let root = dir.path();
4747
    let repo = Repo::init(root).unwrap();
4748
    write(root, "bin", b"\0A");
4749
    let v1 = repo.commit("v1", &[]).unwrap();
4750
    write(root, "bin", b"\0B");
4751
    let v2 = repo.commit("v2", &[]).unwrap();
4752
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
4753
    write(root, "bin", b"\0A");
4754
    let v3 = repo.commit("back to A", &[]).unwrap();
4755
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
4756
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
4757
    let state = repo.load_state(&[v3]).unwrap();
4758
    let snap = state.materialize();
4759
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
4760
        panic!("opaque")
4761
    };
4762
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
4763
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
4764
}
4765
4766
/// Spec §23: a binary file changed on two branches and merged in Git to
4767
/// one side's version comes back as that version at the merge, and the
4768
/// import verifies commit by commit.
4769
#[test]
4770
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
4771
    hermetic();
4772
    if std::process::Command::new("git")
4773
        .arg("--version")
4774
        .output()
4775
        .is_err()
4776
    {
4777
        eprintln!("git not installed; skipping");
4778
        return;
4779
    }
4780
    let dir = tempfile::tempdir().unwrap();
4781
    let root = dir.path();
4782
    let g = root.join("src.git");
4783
    fs::create_dir_all(&g).unwrap();
4784
    let git = |args: &[&str]| -> String {
4785
        let out = std::process::Command::new("git")
4786
            .arg("-C")
4787
            .arg(&g)
4788
            .args([
4789
                "-c",
4790
                "user.name=Grace",
4791
                "-c",
4792
                "[email protected]",
4793
                "-c",
4794
                "commit.gpgsign=false",
4795
            ])
4796
            .args(args)
4797
            .output()
4798
            .unwrap();
4799
        assert!(
4800
            out.status.success(),
4801
            "git {args:?}: {}",
4802
            String::from_utf8_lossy(&out.stderr)
4803
        );
4804
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4805
    };
4806
    git(&["init", "-q", "-b", "main"]);
4807
    write(&g, "logo.bin", b"\0base");
4808
    write(&g, "notes.txt", b"a\nb\nc\n");
4809
    git(&["add", "."]);
4810
    git(&["commit", "-qm", "base"]);
4811
    git(&["checkout", "-qb", "side"]);
4812
    write(&g, "logo.bin", b"\0side");
4813
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
4814
    git(&["commit", "-qam", "side"]);
4815
    git(&["checkout", "-q", "main"]);
4816
    write(&g, "logo.bin", b"\0main");
4817
    git(&["commit", "-qam", "main"]);
4818
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
4819
    let _ = std::process::Command::new("git")
4820
        .arg("-C")
4821
        .arg(&g)
4822
        .args([
4823
            "-c",
4824
            "user.name=G",
4825
            "-c",
4826
            "user.email=g@e",
4827
            "merge",
4828
            "-q",
4829
            "side",
4830
        ])
4831
        .output();
4832
    write(&g, "logo.bin", b"\0main");
4833
    git(&["add", "."]);
4834
    git(&["commit", "-qm", "merge side"]);
4835
    // Then a revert of the binary to its first version.
4836
    write(&g, "logo.bin", b"\0base");
4837
    git(&["commit", "-qam", "back to base"]);
4838
4839
    let repo = Repo::init(&root.join("o")).unwrap();
4840
    let rep = repo.import_git(&g, "main").unwrap();
4841
    assert_eq!(rep.merges, 1);
4842
    let v = repo.verify_git_import(&g, "main").unwrap();
4843
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
4844
    assert_eq!(v.commits, 5);
4845
    let snap = repo
4846
        .load_state(&repo.bookmark_heads().unwrap())
4847
        .unwrap()
4848
        .materialize();
4849
    assert!(!snap.is_conflicted());
4850
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
4851
        panic!("opaque")
4852
    };
4853
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
4854
}
4855
4856
/// Spec §7.7 on a file system without executable bits or symlinks: the
4857
/// recorded bit is kept, and a symlink checked out as a plain file holding
4858
/// its target is still that symlink.
4859
#[cfg(unix)]
4860
#[test]
4861
fn windows_file_systems_keep_exec_bits_and_symlinks() {
4862
    use crate::portable::Platform;
4863
    use std::os::unix::fs::PermissionsExt;
4864
    hermetic();
4865
    let dir = tempfile::tempdir().unwrap();
4866
    let root = dir.path();
4867
    let repo = Repo::init(root).unwrap();
4868
    write(root, "run.sh", b"#!/bin/sh\n");
4869
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
4870
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
4871
    repo.commit("script and link", &[]).unwrap();
4872
    drop(repo);
4873
4874
    // What checking out on Windows leaves: no exec bit, the link as a file.
4875
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
4876
    fs::remove_file(root.join("link")).unwrap();
4877
    write(root, "link", b"run.sh");
4878
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
4879
    let s = win.snapshot("oxy status").unwrap();
4880
    assert!(
4881
        s.statuses.is_empty(),
4882
        "nothing changed on Windows: {:?}",
4883
        statuses(&s)
4884
    );
4885
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
4886
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
4887
    write(root, "link", b"other");
4888
    let h = win.commit("edit on Windows", &[]).unwrap();
4889
    let snap = win.load_state(&[h]).unwrap().materialize();
4890
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
4891
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
4892
    // The same working copy read as Linux sees the lost bit and the plain file.
4893
    let linux = Repo::open(root).unwrap();
4894
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
4895
}
4896
4897
/// Paths that collide on case-insensitive or Windows file systems are
4898
/// named at checkout there, and by doctor everywhere.
4899
#[test]
4900
fn paths_other_platforms_cannot_hold_are_reported() {
4901
    use crate::portable::Platform;
4902
    hermetic();
4903
    let dir = tempfile::tempdir().unwrap();
4904
    let root = dir.path();
4905
    let repo = Repo::init(root).unwrap();
4906
    write(root, "README.md", b"a\n");
4907
    write(root, "readme.md", b"b\n");
4908
    write(root, "src/aux.c", b"int x;\n");
4909
    let h = repo.commit("unportable", &[]).unwrap();
4910
    let r = repo.doctor(false);
4911
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
4912
    assert_eq!(port.health, Health::Warn);
4913
    assert!(
4914
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
4915
        "{}",
4916
        port.message
4917
    );
4918
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
4919
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
4920
    assert!(
4921
        rep.notes
4922
            .iter()
4923
            .any(|n| n.contains("README.md and readme.md")),
4924
        "{:?}",
4925
        rep.notes
4926
    );
4927
    assert!(
4928
        !rep.notes.iter().any(|n| n.contains("aux.c")),
4929
        "macOS allows aux.c"
4930
    );
4931
}
4932
4933
#[test]
4934
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
4935
    hermetic();
4936
    let dir = tempfile::tempdir().unwrap();
4937
    let repo = Repo::init(dir.path()).unwrap();
4938
    write(dir.path(), "a.txt", b"one\n");
4939
    write(dir.path(), "other.txt", b"x\n");
4940
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
4941
    repo.snapshot("t").unwrap();
4942
    let c1 = repo.commit("first", &[]).unwrap();
4943
    write(dir.path(), "other.txt", b"y\n");
4944
    repo.snapshot("t").unwrap();
4945
    repo.commit("other only", &[]).unwrap();
4946
    write(dir.path(), "a.txt", b"one\ntwo\n");
4947
    repo.snapshot("t").unwrap();
4948
    let c3 = repo.commit("second line", &[]).unwrap();
4949
    write(dir.path(), "other.txt", b"z\n");
4950
    repo.snapshot("t").unwrap();
4951
    repo.commit("other again", &[]).unwrap();
4952
4953
    let heads = repo.bookmark_heads().unwrap();
4954
    let state = repo.load_state(&heads).unwrap();
4955
    let full: Vec<ChangeHash> = repo
4956
        .log_for_path_in("a.txt", &heads)
4957
        .unwrap()
4958
        .iter()
4959
        .map(|e| e.hash)
4960
        .collect();
4961
    assert_eq!(
4962
        full,
4963
        vec![c3, c1],
4964
        "newest first, only changes touching the path"
4965
    );
4966
    let newest: Vec<ChangeHash> = repo
4967
        .log_for_path_of(&state, "a.txt", Some(1))
4968
        .unwrap()
4969
        .iter()
4970
        .map(|e| e.hash)
4971
        .collect();
4972
    assert_eq!(newest, vec![c3], "stops at the first");
4973
    assert_eq!(
4974
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
4975
        2
4976
    );
4977
    assert!(repo
4978
        .log_for_path_of(&state, "missing.txt", Some(1))
4979
        .is_err());
4980
    assert_eq!(
4981
        repo.log_state(&heads).unwrap().len(),
4982
        repo.log_of(&state).len()
4983
    );
4984
4985
    let tree = state.tree().view();
4986
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
4987
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
4988
    assert_eq!(
4989
        via_state
4990
            .iter()
4991
            .map(|l| (l.hash, l.text.clone()))
4992
            .collect::<Vec<_>>(),
4993
        via_heads
4994
            .iter()
4995
            .map(|l| (l.hash, l.text.clone()))
4996
            .collect::<Vec<_>>()
4997
    );
4998
    assert_eq!(
4999
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
5000
        vec![c1, c3]
5001
    );
5002
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
5003
}
5004
5005
/// A text file whose stat matches the manifest and whose recorded hash is
5006
/// the base's content is taken from the base without reading it; anything
5007
/// else is read, so no edit is missed (spec §12.3).
5008
#[cfg(unix)]
5009
#[test]
5010
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
5011
    use std::os::unix::fs::PermissionsExt;
5012
    hermetic();
5013
    let dir = tempfile::tempdir().unwrap();
5014
    let root = dir.path();
5015
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5016
    write(root, "a.txt", b"one\ntwo\n");
5017
    write(root, "b.txt", b"bee\n");
5018
    repo.commit("base", &[]).unwrap();
5019
    let age = |p: &str| {
5020
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5021
        fs::File::options()
5022
            .write(true)
5023
            .open(root.join(p))
5024
            .unwrap()
5025
            .set_modified(old)
5026
            .unwrap();
5027
    };
5028
    age("a.txt");
5029
    age("b.txt");
5030
    assert!(
5031
        !repo.snapshot("status").unwrap().changed,
5032
        "records the aged stat"
5033
    );
5034
5035
    // Clean and equal to the base: not read at all.
5036
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5037
    let snap = repo.snapshot("status").unwrap();
5038
    assert!(
5039
        !snap.changed && snap.statuses.is_empty(),
5040
        "{:?}",
5041
        snap.statuses
5042
    );
5043
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5044
5045
    // An uncommitted edit that is older than the manifest: stat-clean, but
5046
    // its hash is not the base's, so it is read and stays visible.
5047
    write(root, "b.txt", b"bee edited\n");
5048
    age("b.txt");
5049
    let first = repo.snapshot("status").unwrap();
5050
    assert_eq!(
5051
        statuses(&first),
5052
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
5053
    );
5054
    let again = repo.snapshot("status").unwrap();
5055
    assert_eq!(
5056
        statuses(&again),
5057
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
5058
        "still seen once stat-clean"
5059
    );
5060
    assert!(!again.changed, "and the working copy hashes the same");
5061
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5062
    assert!(
5063
        repo.snapshot("status").is_err(),
5064
        "an edited file must be read, never taken from the base"
5065
    );
5066
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5067
5068
    // A same-size edit made just now is racy and read.
5069
    write(root, "a.txt", b"one\nTWO\n");
5070
    assert_eq!(
5071
        statuses(&repo.snapshot("status").unwrap()),
5072
        vec![
5073
            ("a.txt".to_string(), ChangeStatus::Modified),
5074
            ("b.txt".to_string(), ChangeStatus::Modified)
5075
        ]
5076
    );
5077
    // Committing makes the edits the base: both are clean and served from it again.
5078
    repo.commit("edits", &[]).unwrap();
5079
    age("a.txt");
5080
    age("b.txt");
5081
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5082
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5083
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5084
    let snap = repo.snapshot("status").unwrap();
5085
    assert!(!snap.changed && snap.statuses.is_empty());
5086
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5087
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5088
}
5089
5090
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
5091
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
5092
/// file is unchanged, and loading through the checkpoint equals a full load.
5093
#[test]
5094
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
5095
    hermetic();
5096
    let dir = tempfile::tempdir().unwrap();
5097
    let root = dir.path();
5098
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5099
    let long: String = (0..300)
5100
        .map(|i| format!("line {i} of a long file\n"))
5101
        .collect();
5102
    write(root, "long.txt", long.as_bytes());
5103
    write(root, "short.txt", b"short\n");
5104
    repo.commit("base", &[]).unwrap();
5105
    let (r1, _, _) = repo.checkpoint().unwrap();
5106
    let cp1 = crate::objects::Checkpoint::decode(
5107
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
5108
    )
5109
    .unwrap();
5110
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
5111
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
5112
5113
    // gc keeps the graph blob; fsck finds the checkpoint sound.
5114
    repo.gc(true).unwrap();
5115
    assert!(repo.store().has(&graphs1[0]));
5116
    let report = repo.fsck().unwrap();
5117
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
5118
5119
    // Loading through the checkpoint equals a full load.
5120
    write(root, "short.txt", b"short, edited\n");
5121
    repo.commit("edit the short file", &[]).unwrap();
5122
    let heads = repo.bookmark_heads().unwrap();
5123
    let fast = repo.load_state(&heads).unwrap();
5124
    let full = repo.load_state_full(&heads).unwrap();
5125
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
5126
5127
    // The next checkpoint shares the unchanged long file's graph.
5128
    let (r2, _, _) = repo.checkpoint().unwrap();
5129
    let cp2 = crate::objects::Checkpoint::decode(
5130
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
5131
    )
5132
    .unwrap();
5133
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
5134
5135
    // A shallow clone's bundle carries the graph blob with the checkpoint.
5136
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
5137
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
5138
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
5139
5140
    // A version 1 checkpoint written by an older oxy still loads.
5141
    let state = repo.load_state_full(&heads).unwrap();
5142
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
5143
    let cp_old = crate::objects::Checkpoint {
5144
        heads: cp2.heads.clone(),
5145
        count: cp2.count,
5146
        payload: old,
5147
    };
5148
    let r_old = repo
5149
        .store()
5150
        .put(ObjectType::Checkpoint, &cp_old.encode())
5151
        .unwrap();
5152
    repo.install_checkpoint("main", &r_old).unwrap();
5153
    assert_eq!(
5154
        repo.load_state(&heads).unwrap().checkpoint_payload(),
5155
        full.checkpoint_payload()
5156
    );
5157
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5158
5159
    // A lost graph blob fails the load loudly rather than dropping the
5160
    // file, and fsck reports it (a fresh repository, objects still loose).
5161
    let dir2 = tempfile::tempdir().unwrap();
5162
    let root2 = dir2.path();
5163
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
5164
    write(root2, "long.txt", long.as_bytes());
5165
    repo2.commit("base", &[]).unwrap();
5166
    let (r, _, _) = repo2.checkpoint().unwrap();
5167
    let cp = crate::objects::Checkpoint::decode(
5168
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
5169
    )
5170
    .unwrap();
5171
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
5172
    repo2.store().remove_loose_for_test(&graph).unwrap();
5173
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
5174
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
5175
}
5176
5177
/// A new repository has not stored the user's identity yet (that happens
5178
/// at the first signed change); looking it up falls back to the key
5179
/// directory, and a file there that does not hash to the key is refused.
5180
#[test]
5181
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
5182
    hermetic();
5183
    let dir = tempfile::tempdir().unwrap();
5184
    let home = dir.path().join("home");
5185
    let mut first = Repo::init(&dir.path().join("a"))
5186
        .unwrap()
5187
        .with_home(home.clone());
5188
    let (key, _) = first
5189
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5190
        .unwrap();
5191
    let fresh = Repo::init(&dir.path().join("b"))
5192
        .unwrap()
5193
        .with_home(home.clone());
5194
    assert!(!fresh.store().has(&key), "nothing stored yet");
5195
    let id = fresh.identity(&key).unwrap();
5196
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
5197
    // A key file that is not this identity is an error, not a wrong answer.
5198
    let keys = fresh.keys_dir.clone();
5199
    let (other, _) = first
5200
        .create_identity("Bob", "[email protected]", IdentityScope::User)
5201
        .unwrap();
5202
    fs::copy(
5203
        keys.join(format!("{}.identity", other.to_hex())),
5204
        keys.join(format!("{}.identity", key.to_hex())),
5205
    )
5206
    .unwrap();
5207
    assert!(fresh
5208
        .identity(&key)
5209
        .unwrap_err()
5210
        .to_string()
5211
        .contains("does not hold identity"));
5212
}
5213
5214
/// Status snapshots (spec §12.3): a text file whose stat matches the
5215
/// manifest, and whose base graph key is the one the manifest recorded it
5216
/// equal to, is neither read nor rendered; any edit, and any change to the
5217
/// file's graph in the base, brings it back.
5218
#[cfg(unix)]
5219
#[test]
5220
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
5221
    use std::os::unix::fs::PermissionsExt;
5222
    hermetic();
5223
    let dir = tempfile::tempdir().unwrap();
5224
    let root = dir.path();
5225
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5226
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
5227
        write(root, p, c.as_bytes());
5228
    }
5229
    repo.commit("base", &[]).unwrap();
5230
    let age = |p: &str| {
5231
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5232
        fs::File::options()
5233
            .write(true)
5234
            .open(root.join(p))
5235
            .unwrap()
5236
            .set_modified(old)
5237
            .unwrap();
5238
    };
5239
    let lock = |p: &str, mode: u32| {
5240
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
5241
    };
5242
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5243
        age(p);
5244
    }
5245
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5246
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
5247
    assert!(
5248
        m.entries.values().all(|e| e.graph.is_some()),
5249
        "keys recorded"
5250
    );
5251
5252
    // Unreadable files prove they are not read; the status snapshot does
5253
    // not render them either, and its base lacks their graphs.
5254
    lock("a.txt", 0o000);
5255
    lock("b.txt", 0o000);
5256
    let snap = repo.snapshot_status("status").unwrap();
5257
    assert!(!snap.changed && snap.statuses.is_empty());
5258
    assert_eq!(
5259
        snap.base_snapshot
5260
            .unrendered
5261
            .iter()
5262
            .cloned()
5263
            .collect::<Vec<_>>(),
5264
        vec!["a.txt", "b.txt", "d/c.txt"]
5265
    );
5266
    assert!(!snap.base.is_full());
5267
    assert!(!snap.base_snapshot.is_conflicted());
5268
    // A full snapshot does not read them either, but renders everything.
5269
    let full = repo.snapshot("status").unwrap();
5270
    assert!(full.statuses.is_empty() && full.base.is_full());
5271
    assert!(full.base_snapshot.unrendered.is_empty());
5272
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
5273
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
5274
5275
    // An edit is seen; the file is rendered, the others still are not.
5276
    write(root, "d/c.txt", b"sea edited\n");
5277
    let snap = repo.snapshot_status("status").unwrap();
5278
    assert_eq!(
5279
        statuses(&snap),
5280
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
5281
    );
5282
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
5283
    // So is a mode change of an unread file.
5284
    lock("b.txt", 0o100);
5285
    assert_eq!(
5286
        statuses(&repo.snapshot_status("status").unwrap()),
5287
        vec![
5288
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
5289
            ("d/c.txt".to_string(), ChangeStatus::Modified)
5290
        ]
5291
    );
5292
    lock("b.txt", 0o000);
5293
5294
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
5295
    // stays unread, c.txt is read once and then skipped too.
5296
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
5297
        .unwrap();
5298
    age("d/c.txt");
5299
    let snap = repo.snapshot_status("status").unwrap();
5300
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
5301
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
5302
    lock("d/c.txt", 0o000);
5303
    let snap = repo.snapshot_status("status").unwrap();
5304
    assert!(snap.statuses.is_empty());
5305
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
5306
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5307
        lock(p, 0o644);
5308
    }
5309
}
5310
5311
/// Attributes decide how a file compares with the base, so a changed
5312
/// `.oxyattributes` makes every text file be compared again.
5313
#[cfg(unix)]
5314
#[test]
5315
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
5316
    hermetic();
5317
    let dir = tempfile::tempdir().unwrap();
5318
    let root = dir.path();
5319
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5320
    write(root, "a.txt", b"crlf\r\n");
5321
    repo.commit("base", &[]).unwrap();
5322
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5323
    fs::File::options()
5324
        .write(true)
5325
        .open(root.join("a.txt"))
5326
        .unwrap()
5327
        .set_modified(old)
5328
        .unwrap();
5329
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5330
    assert!(repo
5331
        .snapshot_status("status")
5332
        .unwrap()
5333
        .base_snapshot
5334
        .unrendered
5335
        .contains("a.txt"));
5336
    // With eol=lf, a.txt as stored no longer equals the base.
5337
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
5338
    let snap = repo.snapshot_status("status").unwrap();
5339
    assert_eq!(
5340
        statuses(&snap),
5341
        vec![
5342
            (".oxyattributes".to_string(), ChangeStatus::Added),
5343
            ("a.txt".to_string(), ChangeStatus::Modified)
5344
        ]
5345
    );
5346
}
5347
5348
/// Bookmarks with `/` in their names: pushing records their
5349
/// attestations, and checkpoints are kept for them, beside `feature`
5350
/// itself.
5351
#[test]
5352
fn bookmarks_with_slashes_push_and_checkpoint() {
5353
    hermetic();
5354
    let dir = tempfile::tempdir().unwrap();
5355
    let root = dir.path();
5356
    let origin = Repo::init(&root.join("origin")).unwrap();
5357
    let url = root.join("origin").to_string_lossy().to_string();
5358
    let mut repo = Repo::clone(&url, &root.join("r"))
5359
        .unwrap()
5360
        .with_home(root.join("home"));
5361
    // With an identity, pushes carry reference attestations: the case
5362
    // that failed, since the attestation is a file named after the bookmark.
5363
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5364
        .unwrap();
5365
    let r = root.join("r");
5366
    write(&r, "a.txt", b"a\n");
5367
    let h_a = repo.commit("a", &[]).unwrap();
5368
    assert!(repo.push("origin", false).unwrap()[0].ok);
5369
    repo.bookmark_create("feature", None).unwrap();
5370
    repo.bookmark_create("feature/x", None).unwrap();
5371
    repo.bookmark_switch("feature/x", false).unwrap();
5372
    write(&r, "b.txt", b"b\n");
5373
    let h_b = repo.commit("b", &[]).unwrap();
5374
    for name in ["feature", "feature/x"] {
5375
        let res = repo.push_bookmark("origin", name, false).unwrap();
5376
        assert!(res[0].ok, "{name}: {res:?}");
5377
    }
5378
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
5379
    assert_eq!(
5380
        origin.resolve_heads("feature/x").unwrap(),
5381
        repo.resolve_heads("feature/x").unwrap()
5382
    );
5383
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
5384
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
5385
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
5386
5387
    // A checkpoint of feature/x is found again when loading its state.
5388
    let (cp, _, _) = repo.checkpoint().unwrap();
5389
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
5390
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
5391
    let heads = repo.resolve_heads("feature/x").unwrap();
5392
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
5393
}
5394
5395
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
5396
/// never the remote's own bookmark, and a bookmark created again later is
5397
/// accepted although the deletion's attestation stays the latest.
5398
#[test]
5399
fn bookmarks_are_deleted_on_a_remote() {
5400
    hermetic();
5401
    let dir = tempfile::tempdir().unwrap();
5402
    let root = dir.path();
5403
    let origin = Repo::init(&root.join("origin")).unwrap();
5404
    let url = root.join("origin").to_string_lossy().to_string();
5405
    let mut repo = Repo::clone(&url, &root.join("r"))
5406
        .unwrap()
5407
        .with_home(root.join("home"));
5408
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5409
        .unwrap();
5410
    let r = root.join("r");
5411
    write(&r, "a.txt", b"a\n");
5412
    repo.commit("a", &[]).unwrap();
5413
    assert!(repo.push("origin", false).unwrap()[0].ok);
5414
    repo.bookmark_create("feature/x", None).unwrap();
5415
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
5416
    assert!(origin.resolve_heads("feature/x").is_ok());
5417
5418
    let res = repo.push_delete("origin", "feature/x").unwrap();
5419
    assert!(res[0].ok, "{res:?}");
5420
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
5421
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
5422
    assert!(
5423
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
5424
        "the deletion is attested"
5425
    );
5426
    assert!(
5427
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
5428
        "the local bookmark stays"
5429
    );
5430
    assert!(!repo
5431
        .view()
5432
        .unwrap()
5433
        .remotes
5434
        .get("origin")
5435
        .is_some_and(|m| m.contains_key("feature/x")));
5436
5437
    // Pushing it again creates it again, past the deletion's serial.
5438
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
5439
    assert!(res[0].ok, "{res:?}");
5440
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
5441
5442
    // Nothing to delete, and never the remote's own bookmark.
5443
    assert!(repo.push_delete("origin", "nope").is_err());
5444
    let res = repo.push_delete("origin", "main").unwrap();
5445
    assert!(
5446
        !res[0].ok && res[0].reason.contains("default bookmark"),
5447
        "{res:?}"
5448
    );
5449
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
5450
}
5451
5452
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
5453
/// when the target has the same versions of the files it touches, and is
5454
/// refused, untouched, when it has others.
5455
#[test]
5456
fn switching_bookmarks_carries_uncommitted_work() {
5457
    hermetic();
5458
    let dir = tempfile::tempdir().unwrap();
5459
    let root = dir.path();
5460
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5461
    write(root, "a.txt", b"a\n");
5462
    write(root, "b.txt", b"b\n");
5463
    write(root, "gone.txt", b"gone\n");
5464
    repo.commit("base", &[]).unwrap();
5465
    repo.bookmark_create("feature", None).unwrap();
5466
    // Started on main, belongs on feature: edit, add, remove.
5467
    write(root, "a.txt", b"a\nmore\n");
5468
    write(root, "new.txt", b"new\n");
5469
    fs::remove_file(root.join("gone.txt")).unwrap();
5470
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
5471
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
5472
    assert_eq!(repo.config.bookmark, "feature");
5473
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
5474
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
5475
    assert!(!root.join("gone.txt").exists());
5476
    let snap = repo.snapshot("status").unwrap();
5477
    assert_eq!(
5478
        statuses(&snap),
5479
        vec![
5480
            ("a.txt".to_string(), ChangeStatus::Modified),
5481
            ("gone.txt".to_string(), ChangeStatus::Removed),
5482
            ("new.txt".to_string(), ChangeStatus::Added)
5483
        ]
5484
    );
5485
    repo.commit("the work", &[]).unwrap();
5486
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
5487
5488
    // main moves b.txt on; work on feature touching b.txt cannot follow.
5489
    repo.bookmark_switch("main", false).unwrap();
5490
    write(root, "b.txt", b"b on main\n");
5491
    repo.commit("b on main", &[]).unwrap();
5492
    repo.bookmark_switch("feature", false).unwrap();
5493
    write(root, "b.txt", b"b edited\n");
5494
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
5495
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
5496
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
5497
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
5498
}
5499
5500
/// Merging and checking out (feedback 3): a working copy without changes
5501
/// follows a merge whichever state it sat on; a refused checkout names
5502
/// what is in the way; `checkout --carry` takes the work along.
5503
#[test]
5504
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
5505
    hermetic();
5506
    let dir = tempfile::tempdir().unwrap();
5507
    let root = dir.path();
5508
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5509
    write(root, "a.txt", b"a\n");
5510
    let h1 = repo.commit("a", &[]).unwrap();
5511
    write(root, "b.txt", b"b\n");
5512
    repo.commit("b", &[]).unwrap();
5513
    repo.bookmark_create("feature", None).unwrap();
5514
    repo.bookmark_switch("feature", false).unwrap();
5515
    write(root, "c.txt", b"c\n");
5516
    repo.commit("c on feature", &[]).unwrap();
5517
    repo.bookmark_switch("main", false).unwrap();
5518
    // The working copy sits on an older state than main's heads.
5519
    repo.checkout(&[h1], false, "checkout").unwrap();
5520
    assert!(!root.join("b.txt").exists());
5521
    let m = repo.merge("feature").unwrap();
5522
    assert!(m.checked_out, "a clean working copy follows the merge");
5523
    for f in ["a.txt", "b.txt", "c.txt"] {
5524
        assert!(root.join(f).exists(), "{f}");
5525
    }
5526
5527
    // A refusal says which paths are in the way and what to do.
5528
    fs::remove_file(root.join("b.txt")).unwrap();
5529
    write(root, "a.txt", b"a edited\n");
5530
    let err = repo
5531
        .checkout(&[h1], false, "checkout")
5532
        .unwrap_err()
5533
        .to_string();
5534
    assert!(
5535
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
5536
        "{err}"
5537
    );
5538
    // --carry takes them along: h1 has a.txt as the base has it, and no b.txt
5539
    // is carried as absent (h1 has none either, so that is refused).
5540
    let err = repo
5541
        .checkout_carry(&[h1], "the first change", "checkout")
5542
        .unwrap_err()
5543
        .to_string();
5544
    assert!(
5545
        err.contains("b.txt") && err.contains("the first change"),
5546
        "{err}"
5547
    );
5548
    write(root, "b.txt", b"b\n");
5549
    let (_, carried) = repo
5550
        .checkout_carry(&[h1], "the first change", "checkout")
5551
        .unwrap();
5552
    assert_eq!(carried, vec!["a.txt"]);
5553
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
5554
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
5555
}
5556
5557
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
5558
/// user identity not stored in a new repository yet is fine while its
5559
/// secret key is there; an added subrepo is listed as not committed yet.
5560
#[test]
5561
fn a_new_repository_is_healthy_before_its_first_commit() {
5562
    hermetic();
5563
    let dir = tempfile::tempdir().unwrap();
5564
    let root = dir.path();
5565
    let home = root.join("home");
5566
    let mut first = Repo::init(&root.join("first"))
5567
        .unwrap()
5568
        .with_home(home.clone());
5569
    let (key, _) = first
5570
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5571
        .unwrap();
5572
    let repo = Repo::init(&root.join("second"))
5573
        .unwrap()
5574
        .with_home(home.clone());
5575
    // Only the secret key: no identity object anywhere this repository sees.
5576
    let keys = repo.keys_dir.clone();
5577
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
5578
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
5579
    let r = repo.doctor(true);
5580
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
5581
    assert_eq!(id.health, Health::Ok, "{}", id.message);
5582
    assert!(id.message.contains("first signed change"), "{}", id.message);
5583
5584
    // A subrepo added and not committed yet is listed, pinned where it is.
5585
    let lib = root.join("lib");
5586
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
5587
    write(&lib, "x.txt", b"x\n");
5588
    l.commit("x", &[]).unwrap();
5589
    let second = root.join("second");
5590
    write(&second, "a.txt", b"a\n");
5591
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
5592
        .unwrap();
5593
    let subs = repo.subrepos().unwrap();
5594
    assert_eq!(subs.len(), 1);
5595
    assert_eq!(
5596
        (subs[0].path.as_str(), subs[0].committed),
5597
        ("deps/lib", false)
5598
    );
5599
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
5600
    repo.commit("add lib", &[]).unwrap();
5601
    let subs = repo.subrepos().unwrap();
5602
    assert!(subs[0].committed, "committed now");
5603
}
5604
5605
/// Commit, diff, hunks and discard use the partial snapshot: a file
5606
/// unchanged since the manifest is neither read nor rendered, and showing
5607
/// a change renders only what it edits, the same as from a full base.
5608
#[cfg(unix)]
5609
#[test]
5610
fn commits_and_diffs_leave_unchanged_files_alone() {
5611
    use std::os::unix::fs::PermissionsExt;
5612
    hermetic();
5613
    let dir = tempfile::tempdir().unwrap();
5614
    let root = dir.path();
5615
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5616
    write(root, "big.txt", b"lots\nof\nlines\n");
5617
    write(root, "a.txt", b"one\ntwo\n");
5618
    repo.commit("base", &[]).unwrap();
5619
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5620
    for f in ["big.txt", "a.txt"] {
5621
        fs::File::options()
5622
            .write(true)
5623
            .open(root.join(f))
5624
            .unwrap()
5625
            .set_modified(old)
5626
            .unwrap();
5627
    }
5628
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5629
    // big.txt cannot be read at all from here on.
5630
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5631
5632
    write(root, "a.txt", b"one\nTWO\nthree\n");
5633
    let diff = repo.diff_files(None).unwrap();
5634
    assert_eq!(
5635
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
5636
        ["a.txt"]
5637
    );
5638
    let (_, hunks) = repo.hunks().unwrap();
5639
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
5640
    let h = repo.commit("edit a", &[]).unwrap();
5641
5642
    // Showing the change needs only a.txt's graph, and renders as a full base does.
5643
    let c = repo.store().get_change(&h).unwrap();
5644
    let full = repo.load_state(&c.deps).unwrap();
5645
    let want = render_change(&c, &full, &full.materialize());
5646
    assert_eq!(repo.describe_change(&h).unwrap(), want);
5647
    let (base, snap) = repo.change_base(&c).unwrap();
5648
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
5649
5650
    // Discarding works the same way.
5651
    write(root, "a.txt", b"scratch\n");
5652
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
5653
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
5654
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5655
}
5656
5657
/// A replace conflict (spec §9.3) is settled by a change that writes one
5658
/// candidate, or new bytes, at the path when the caller names it; a plain
5659
/// snapshot of a checkout never settles it on its own.
5660
#[test]
5661
fn replace_conflicts_are_settled_when_asked() {
5662
    hermetic();
5663
    let dir = tempfile::tempdir().unwrap();
5664
    let root = dir.path();
5665
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5666
    let blob = |n: u8| {
5667
        let mut v = vec![0u8; 64];
5668
        v[1] = n;
5669
        v
5670
    };
5671
    write(root, "img.bin", &blob(1));
5672
    repo.commit("add img", &[]).unwrap();
5673
    repo.bookmark_create("other", None).unwrap();
5674
    write(root, "img.bin", &blob(2));
5675
    repo.commit("img two", &[]).unwrap();
5676
    repo.bookmark_switch("other", false).unwrap();
5677
    write(root, "img.bin", &blob(3));
5678
    repo.commit("img three", &[]).unwrap();
5679
    repo.bookmark_switch("main", false).unwrap();
5680
    repo.merge("other").unwrap();
5681
    let heads = repo.bookmark_heads().unwrap();
5682
    let merged = repo.load_state(&heads).unwrap().materialize();
5683
    assert!(
5684
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
5685
        "a replace conflict"
5686
    );
5687
    // A snapshot of the checkout records nothing.
5688
    assert!(repo
5689
        .snapshot("status")
5690
        .unwrap()
5691
        .statuses
5692
        .iter()
5693
        .all(|s| s.path != "img.bin"));
5694
5695
    // Keeping candidate 3 settles it.
5696
    let author = repo.author();
5697
    let edits = [FileEdit {
5698
        path: "img.bin".into(),
5699
        content: Some(blob(3)),
5700
    }];
5701
    let c = repo
5702
        .build_change(&heads, &edits, "keep three", author)
5703
        .unwrap();
5704
    assert_eq!(c.kind, ChangeKind::Resolution);
5705
    let mut st = repo.load_state(&heads).unwrap();
5706
    for d in &c.deps {
5707
        assert!(st.contains(d));
5708
    }
5709
    assert!(
5710
        heads.iter().all(|h| c.deps.contains(h)),
5711
        "depends on both contributors"
5712
    );
5713
    st.add(c).unwrap();
5714
    let after = st.materialize();
5715
    assert!(!after.is_conflicted());
5716
    assert_eq!(
5717
        after.files["img.bin"].content,
5718
        FileContent::Opaque {
5719
            blobs: vec![Repo::blob_ref(&blob(3))]
5720
        }
5721
    );
5722
5723
    // New bytes settle it too.
5724
    let edits = [FileEdit {
5725
        path: "img.bin".into(),
5726
        content: Some(blob(9)),
5727
    }];
5728
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
5729
    let mut st = repo.load_state(&heads).unwrap();
5730
    st.add(c).unwrap();
5731
    assert_eq!(
5732
        st.materialize().files["img.bin"].content,
5733
        FileContent::Opaque {
5734
            blobs: vec![Repo::blob_ref(&blob(9))]
5735
        }
5736
    );
5737
}
5738
5739
/// The history of a range of lines (spec §27): the changes that wrote
5740
/// or deleted its atoms, or deleted atoms from between them; edits outside
5741
/// the range and changes the range's lines survived are not in it.
5742
#[test]
5743
fn line_ranges_have_exact_histories() {
5744
    hermetic();
5745
    let dir = tempfile::tempdir().unwrap();
5746
    let root = dir.path();
5747
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5748
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
5749
    let base = repo.commit("add f", &[]).unwrap();
5750
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
5751
    let outside = repo.commit("change the import", &[]).unwrap();
5752
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
5753
    let inside = repo.commit("edit a line of a", &[]).unwrap();
5754
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
5755
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
5756
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
5757
    let after = repo.commit("add b after a", &[]).unwrap();
5758
    let heads = repo.bookmark_heads().unwrap();
5759
5760
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
5761
    let hist: Vec<ChangeHash> = repo
5762
        .line_history(&heads, "f.rs", 2, 4)
5763
        .unwrap()
5764
        .iter()
5765
        .map(|e| e.hash)
5766
        .collect();
5767
    for (h, what) in [
5768
        (base, "wrote it"),
5769
        (inside, "edited a line"),
5770
        (deleted, "deleted a line from inside"),
5771
    ] {
5772
        assert!(hist.contains(&h), "{what}");
5773
    }
5774
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
5775
        assert!(!hist.contains(&h), "{what}");
5776
    }
5777
    assert_eq!(hist[0], deleted, "newest first");
5778
    // One line: only what touched it.
5779
    let one: Vec<ChangeHash> = repo
5780
        .line_history(&heads, "f.rs", 1, 1)
5781
        .unwrap()
5782
        .iter()
5783
        .map(|e| e.hash)
5784
        .collect();
5785
    assert!(one.contains(&outside) && !one.contains(&inside));
5786
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
5787
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
5788
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
5789
}
5790
5791
#[test]
5792
fn receipts_are_kept_with_their_state_and_verified() {
5793
    use crate::receipt::{Receipt, SignedReceipt};
5794
    hermetic();
5795
    let dir = tempfile::tempdir().unwrap();
5796
    let root = dir.path();
5797
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5798
    write(root, "a.txt", b"1\n");
5799
    repo.commit("A", &[]).unwrap();
5800
    let heads = repo.bookmark_heads().unwrap();
5801
    let state = repo
5802
        .store()
5803
        .put_state(&StateObject::new(heads.clone()))
5804
        .unwrap();
5805
    let out = repo.store_blob(b"built\n").unwrap();
5806
    let receipt = Receipt {
5807
        job_name: "build".into(),
5808
        pipeline_hash: ObjectRef([1; 32]),
5809
        scope_tree_hash: ObjectRef([2; 32]),
5810
        inputs: vec![],
5811
        environment: ObjectRef([3; 32]),
5812
        outputs: vec![out],
5813
        exit_code: 0,
5814
        duration_ms: 42,
5815
    };
5816
    let sk = SecretKey::generate();
5817
    let runner = sk.identity("earth-1", "runner@earth", 1);
5818
    let sr = SignedReceipt::sign(
5819
        receipt.clone(),
5820
        repo.id().unwrap(),
5821
        state,
5822
        "demo#1",
5823
        &runner,
5824
        &sk,
5825
    );
5826
5827
    let r = repo.add_receipt(&sr).unwrap();
5828
    let found = repo.receipts(&heads).unwrap();
5829
    assert_eq!(found.len(), 1);
5830
    assert_eq!(found[0].attest, r);
5831
    assert_eq!(found[0].signed, sr);
5832
    assert!(found[0].problem.is_none() && !found[0].revoked);
5833
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
5834
5835
    // Another repository's receipt, or a forged one, is refused.
5836
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
5837
    assert!(repo
5838
        .add_receipt(&elsewhere)
5839
        .unwrap_err()
5840
        .to_string()
5841
        .contains("another repository"));
5842
    let mut forged = sr.clone();
5843
    forged.receipt.exit_code = 1;
5844
    assert!(repo
5845
        .add_receipt(&forged)
5846
        .unwrap_err()
5847
        .to_string()
5848
        .contains("does not verify"));
5849
5850
    // gc keeps the receipt, its runner and its output while the state lives.
5851
    repo.gc(true).unwrap();
5852
    assert_eq!(repo.receipts(&heads).unwrap().len(), 1);
5853
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
5854
    assert!(repo.fsck().unwrap().problems.is_empty());
5855
}
5856
5857
#[test]
5858
fn status_leaves_an_unchanged_manifest_alone() {
5859
    hermetic();
5860
    let dir = tempfile::tempdir().unwrap();
5861
    let root = dir.path();
5862
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5863
    write(root, "a.txt", b"1\n");
5864
    write(root, "b.txt", b"2\n");
5865
    repo.commit("A", &[]).unwrap();
5866
    // Files last touched well outside the racy window.
5867
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
5868
    for f in ["a.txt", "b.txt"] {
5869
        fs::File::options()
5870
            .write(true)
5871
            .open(root.join(f))
5872
            .unwrap()
5873
            .set_modified(old)
5874
            .unwrap();
5875
    }
5876
    repo.snapshot_status("status").unwrap();
5877
    let path = repo.manifest_path();
5878
    let first = fs::read(&path).unwrap();
5879
    repo.snapshot_status("status").unwrap();
5880
    assert_eq!(
5881
        fs::read(&path).unwrap(),
5882
        first,
5883
        "an unchanged tree does not rewrite the manifest"
5884
    );
5885
    // A change rewrites it.
5886
    write(root, "a.txt", b"1\n2\n");
5887
    repo.snapshot_status("status").unwrap();
5888
    assert_ne!(fs::read(&path).unwrap(), first);
5889
}
5890
5891
#[test]
5892
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
5893
    hermetic();
5894
    let dir = tempfile::tempdir().unwrap();
5895
    let root = dir.path();
5896
    let origin_path = root.join("origin");
5897
    Repo::init(&origin_path).unwrap();
5898
    let origin_url = origin_path.to_string_lossy().to_string();
5899
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
5900
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
5901
    write(&root.join("a"), "big.txt", big.as_bytes());
5902
    write(&root.join("a"), "small.txt", b"small\n");
5903
    let h1 = a.commit("large", &[]).unwrap();
5904
    let (_, body) = a.store().get(&h1).unwrap();
5905
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
5906
    assert!(a.push("origin", false).unwrap()[0].ok);
5907
5908
    // A clone reads the text from the blobs that came with the change.
5909
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
5910
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
5911
    // An edit in the middle of the stored insert is an ordinary change.
5912
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
5913
    write(&root.join("b"), "big.txt", edited.as_bytes());
5914
    let h2 = b.commit("edit", &[]).unwrap();
5915
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
5916
    assert!(b.push("origin", false).unwrap()[0].ok);
5917
    assert!(a.pull("origin").unwrap().checked_out);
5918
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
5919
    assert_eq!(
5920
        a.fsck().unwrap().errors(),
5921
        0,
5922
        "{:?}",
5923
        a.fsck().unwrap().problems
5924
    );
5925
5926
    // With zero retention gc keeps the text blobs of every kept change.
5927
    let mut a = Repo::open(&root.join("a")).unwrap();
5928
    a.config.set("core.op-retention", "0").unwrap();
5929
    a.save_config().unwrap();
5930
    let a = Repo::open(&root.join("a")).unwrap();
5931
    a.gc(true).unwrap();
5932
    let a = Repo::open(&root.join("a")).unwrap();
5933
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
5934
    assert_eq!(
5935
        a.fsck().unwrap().errors(),
5936
        0,
5937
        "{:?}",
5938
        a.fsck().unwrap().problems
5939
    );
5940
    // And a clone of the packed repository reads them from its packs.
5941
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
5942
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
5943
    drop(c);
5944
}
5945
5946
#[test]
5947
fn operations_that_both_replace_a_working_copy_are_not_merged() {
5948
    hermetic();
5949
    let dir = tempfile::tempdir().unwrap();
5950
    let root = dir.path();
5951
    let repo = Repo::init(root).unwrap();
5952
    write(root, "a.txt", b"a\n");
5953
    let a = repo.commit("a", &[]).unwrap();
5954
    write(root, "b.txt", b"b\n");
5955
    repo.commit("b", &[]).unwrap();
5956
    let (x, op) = repo.head_op().unwrap();
5957
    let ws = *op.view.workspaces.keys().next().unwrap();
5958
    let mut one = op.view.clone();
5959
    one.workspaces.insert(ws, a);
5960
    let mut two = op.view.clone();
5961
    two.workspaces.insert(ws, ObjectRef([7; 32]));
5962
    let first = repo.record_op(&[x], "one", one).unwrap();
5963
    let e = repo.record_op(&[x], "two", two).unwrap_err();
5964
    assert!(
5965
        e.to_string()
5966
            .contains("changed this working copy at the same time"),
5967
        "{e}"
5968
    );
5969
    assert_eq!(
5970
        repo.head_op().unwrap().0,
5971
        first,
5972
        "the second is not recorded"
5973
    );
5974
}
5975
5976
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
5977
/// rewrote the working copy recorded the half-written files as edits, and
5978
/// its view replaced the switch's.
5979
#[test]
5980
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
5981
    hermetic();
5982
    let dir = tempfile::tempdir().unwrap();
5983
    let root = dir.path().to_path_buf();
5984
    let mut repo = Repo::init(&root).unwrap();
5985
    write(&root, "keep.txt", b"keep\n");
5986
    repo.commit("base", &[]).unwrap();
5987
    repo.bookmark_create("small", None).unwrap();
5988
    for i in 0..300 {
5989
        write(
5990
            &root,
5991
            &format!("many/f{i}.txt"),
5992
            format!("file {i}\n").as_bytes(),
5993
        );
5994
    }
5995
    repo.commit("many", &[]).unwrap();
5996
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
5997
    let watcher = {
5998
        let (root, stop) = (root.clone(), stop.clone());
5999
        std::thread::spawn(move || {
6000
            let r = Repo::open(&root).unwrap();
6001
            let mut ran = 0;
6002
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
6003
                if r.snapshot_status("oxy status").is_ok() {
6004
                    ran += 1;
6005
                }
6006
            }
6007
            ran
6008
        })
6009
    };
6010
    for i in 0..20 {
6011
        let to = if i % 2 == 0 { "small" } else { "main" };
6012
        repo.bookmark_switch(to, false).unwrap();
6013
    }
6014
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
6015
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
6016
    // Back on main, clean, with every file where main has it.
6017
    let repo = Repo::open(&root).unwrap();
6018
    let s = repo.snapshot_status("oxy status").unwrap();
6019
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
6020
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
6021
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
6022
    assert!(root.join("many/f299.txt").exists());
6023
}
6024
6025
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
6026
/// put a subrepo that was ahead of its pin back at the pin and moved the
6027
/// subrepo's own bookmark backwards.
6028
#[test]
6029
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
6030
    hermetic();
6031
    let dir = tempfile::tempdir().unwrap();
6032
    let root = dir.path();
6033
    Repo::init(&root.join("lib-origin")).unwrap();
6034
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
6035
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
6036
    write(&root.join("lib"), "lib.txt", b"v1\n");
6037
    lib.commit("lib v1", &[]).unwrap();
6038
    assert!(lib.push("origin", false).unwrap()[0].ok);
6039
6040
    let app_dir = root.join("app");
6041
    let mut app = Repo::init(&app_dir).unwrap();
6042
    write(&app_dir, "main.txt", b"app\n");
6043
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
6044
    app.commit("app with lib", &[]).unwrap();
6045
    app.bookmark_create("feature", None).unwrap();
6046
6047
    // New work in the subrepo, not yet pinned by the parent.
6048
    let nested_dir = app_dir.join("libs/lib");
6049
    let nested = Repo::open(&nested_dir).unwrap();
6050
    write(&nested_dir, "new.txt", b"new\n");
6051
    let l2 = nested.commit("lib: new file", &[]).unwrap();
6052
    drop(nested);
6053
6054
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
6055
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
6056
    let nested = Repo::open(&nested_dir).unwrap();
6057
    assert!(
6058
        nested.bookmark_heads().unwrap().contains(&l2),
6059
        "its bookmark kept its work"
6060
    );
6061
    assert!(nested_dir.join("new.txt").exists(), "and its files");
6062
    let s = app.snapshot("status").unwrap();
6063
    assert_eq!(
6064
        statuses(&s),
6065
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
6066
    );
6067
}
6068
6069
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
6070
/// moving `main` to a change this clone had pushed on another bookmark,
6071
/// the first `pull` said "Already up to date" while `main` was behind.
6072
#[test]
6073
fn pull_takes_a_remote_move_to_changes_already_here() {
6074
    hermetic();
6075
    let dir = tempfile::tempdir().unwrap();
6076
    let root = dir.path();
6077
    let origin_path = root.join("origin");
6078
    let origin = Repo::init(&origin_path).unwrap();
6079
    let url = origin_path.to_string_lossy().to_string();
6080
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
6081
    write(&root.join("b"), "base.txt", b"base\n");
6082
    b.commit("base", &[]).unwrap();
6083
    assert!(b.push("origin", false).unwrap()[0].ok);
6084
6085
    // A feature bookmark with one change, pushed.
6086
    b.bookmark_create("feat", None).unwrap();
6087
    b.bookmark_switch("feat", false).unwrap();
6088
    write(&root.join("b"), "x.txt", b"x\n");
6089
    let x = b.commit("x", &[]).unwrap();
6090
    assert!(b.push("origin", false).unwrap()[0].ok);
6091
    b.bookmark_switch("main", false).unwrap();
6092
6093
    // The remote lands it: its main moves to the feature's state.
6094
    let feat = origin
6095
        .store()
6096
        .get_state(&origin.view().unwrap().bookmarks["feat"])
6097
        .unwrap()
6098
        .heads;
6099
    origin.bookmark_set("main", &feat).unwrap();
6100
6101
    let r = b.pull("origin").unwrap();
6102
    assert!(r.changed, "{r:?}");
6103
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
6104
    let main = b
6105
        .bookmarks()
6106
        .unwrap()
6107
        .into_iter()
6108
        .find(|m| m.name == "main")
6109
        .unwrap();
6110
    assert_eq!(main.behind, Some(0), "{main:?}");
6111
}
6112
6113
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
6114
/// to one only the remote has makes a local bookmark from it; a pull moves
6115
/// every local bookmark the remote has too; a clone checks out the remote's
6116
/// default bookmark.
6117
#[test]
6118
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
6119
    hermetic();
6120
    let dir = tempfile::tempdir().unwrap();
6121
    let root = dir.path();
6122
    let origin_path = root.join("origin");
6123
    let mut origin = Repo::init(&origin_path).unwrap();
6124
    let url = origin_path.to_string_lossy().to_string();
6125
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
6126
    write(&root.join("a"), "base.txt", b"base\n");
6127
    a.commit("base", &[]).unwrap();
6128
    assert!(a.push("origin", false).unwrap()[0].ok);
6129
    a.bookmark_create("develop", None).unwrap();
6130
    a.bookmark_switch("develop", false).unwrap();
6131
    write(&root.join("a"), "base.txt", b"base\nd1\n");
6132
    let d1 = a.commit("d1", &[]).unwrap();
6133
    assert!(a.push("origin", false).unwrap()[0].ok);
6134
6135
    // A clone has main only; origin/develop is a name all the same.
6136
    let c_root = root.join("c");
6137
    let mut c = Repo::clone(&url, &c_root).unwrap();
6138
    assert_eq!(c.config.bookmark, "main");
6139
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
6140
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
6141
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
6142
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
6143
6144
    // Switching makes the local bookmark from origin's.
6145
    c.bookmark_switch("develop", false).unwrap();
6146
    assert_eq!(c.config.bookmark, "develop");
6147
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
6148
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
6149
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
6150
    assert!(c.bookmark_switch("nowhere", false).is_err());
6151
6152
    // Both bookmarks move on the remote; one pull takes both.
6153
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
6154
    let d2 = a.commit("d2", &[]).unwrap();
6155
    assert!(a.push("origin", false).unwrap()[0].ok);
6156
    a.bookmark_switch("main", false).unwrap();
6157
    write(&root.join("a"), "m.txt", b"m\n");
6158
    let m = a.commit("m", &[]).unwrap();
6159
    assert!(a.push("origin", false).unwrap()[0].ok);
6160
    let r = c.pull("origin").unwrap();
6161
    assert!(r.changed && r.checked_out, "{r:?}");
6162
    assert_eq!(r.heads, vec![d2]);
6163
    assert_eq!(r.others, vec!["main".to_string()]);
6164
    assert!(c.resolve_heads("main").unwrap().contains(&m));
6165
    assert_eq!(
6166
        fs::read(c_root.join("base.txt")).unwrap(),
6167
        b"base\nd1\nd2\n"
6168
    );
6169
    let again = c.pull("origin").unwrap();
6170
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
6171
6172
    // A clone checks out the remote's default bookmark.
6173
    origin.config.set("workspace.bookmark", "develop").unwrap();
6174
    origin.save_config().unwrap();
6175
    let e = Repo::clone(&url, &root.join("e")).unwrap();
6176
    assert_eq!(e.config.bookmark, "develop");
6177
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
6178
    let reopened = Repo::open(&root.join("e")).unwrap();
6179
    assert_eq!(reopened.config.bookmark, "develop");
6180
    // REMOTE/NAME names the remote's bookmark to switch to.
6181
    let mut e = reopened;
6182
    e.bookmark_switch("origin/main", false).unwrap();
6183
    assert_eq!(e.config.bookmark, "main");
6184
    assert!(e.bookmark_heads().unwrap().contains(&m));
6185
}
6186
6187
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
6188
/// op restore goes back to an operation, files included, and undo takes
6189
/// the restore back whole; op revert undoes one operation alone; each
6190
/// operation's changes are described from the views.
6191
#[test]
6192
fn operations_can_be_read_restored_and_reverted() {
6193
    hermetic();
6194
    let dir = tempfile::tempdir().unwrap();
6195
    let root = dir.path();
6196
    let repo = Repo::init(root).unwrap();
6197
    write(root, "a.txt", b"a\n");
6198
    let first = repo.commit("first", &[]).unwrap();
6199
    write(root, "a.txt", b"a\nb\n");
6200
    let second = repo.commit("second", &[]).unwrap();
6201
    let at_second = repo.head_op().unwrap().0.to_hex();
6202
    repo.bookmark_create("keep", None).unwrap();
6203
    let created = repo.head_op().unwrap().0.to_hex();
6204
    write(root, "n.txt", b"n\n");
6205
    let third = repo.commit("third", &[]).unwrap();
6206
6207
    // What each operation changed.
6208
    let ops = repo.op_log().unwrap();
6209
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
6210
    assert!(
6211
        changes
6212
            .iter()
6213
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
6214
        "{changes:?}"
6215
    );
6216
    assert!(changes
6217
        .iter()
6218
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
6219
6220
    // Reading at an earlier operation.
6221
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
6222
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
6223
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
6224
    write(root, "z.txt", b"z\n");
6225
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
6226
    fs::remove_file(root.join("z.txt")).unwrap();
6227
    assert!(repo.resolve_op("zz").is_err());
6228
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
6229
6230
    // Restore goes back, files and all; undo takes it back whole.
6231
    repo.op_restore(&at_second, false).unwrap();
6232
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
6233
    assert!(!root.join("n.txt").exists());
6234
    repo.undo().unwrap();
6235
    let mut heads = repo.bookmark_heads().unwrap();
6236
    heads.sort();
6237
    let mut want = vec![second, third];
6238
    want.sort();
6239
    assert_eq!(heads, want);
6240
    assert!(
6241
        root.join("n.txt").exists(),
6242
        "the files came back with the undo"
6243
    );
6244
6245
    // Revert the bookmark's creation alone: the commit after it stays.
6246
    let r = repo.op_revert(&created).unwrap();
6247
    assert_eq!(r.reverted, vec!["keep".to_string()]);
6248
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
6249
    assert!(repo
6250
        .load_state(&repo.bookmark_heads().unwrap())
6251
        .unwrap()
6252
        .contains(&third));
6253
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
6254
    let _ = first;
6255
}
6256
6257
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
6258
/// from the status cache while every file is as the snapshot left it, and
6259
/// from a snapshot again as soon as one is not.
6260
#[test]
6261
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
6262
    hermetic();
6263
    let dir = tempfile::tempdir().unwrap();
6264
    let root = dir.path();
6265
    let repo = Repo::init(root).unwrap();
6266
    write(root, "a.txt", b"a\n");
6267
    write(root, "b.txt", b"b\n");
6268
    repo.commit("base", &[]).unwrap();
6269
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
6270
6271
    write(root, "a.txt", b"a\nmore\n");
6272
    assert_eq!(
6273
        repo.status_by_manifest().unwrap(),
6274
        None,
6275
        "no snapshot of the edit yet"
6276
    );
6277
    let snap = repo.snapshot_status("oxy status").unwrap();
6278
    assert_eq!(snap.statuses.len(), 1);
6279
    let cached = repo
6280
        .status_by_manifest()
6281
        .unwrap()
6282
        .expect("answered from the cache");
6283
    assert_eq!(cached.len(), 1);
6284
    assert_eq!(
6285
        (cached[0].path.as_str(), cached[0].status),
6286
        ("a.txt", ChangeStatus::Modified)
6287
    );
6288
6289
    // Any further change sends status back to a snapshot.
6290
    write(root, "a.txt", b"a\nmore\nand more\n");
6291
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
6292
    repo.snapshot_status("oxy status").unwrap();
6293
    assert!(repo.status_by_manifest().unwrap().is_some());
6294
    write(root, "new.txt", b"n\n");
6295
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
6296
    fs::remove_file(root.join("new.txt")).unwrap();
6297
    assert!(
6298
        repo.status_by_manifest().unwrap().is_some(),
6299
        "back as it was"
6300
    );
6301
    fs::remove_file(root.join("b.txt")).unwrap();
6302
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
6303
    write(root, "b.txt", b"b\n");
6304
6305
    // A commit leaves nothing uncommitted: clean again, no cache needed.
6306
    repo.snapshot_status("oxy status").unwrap();
6307
    repo.commit("more", &[]).unwrap();
6308
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6309
}
6310
6311
/// oxygen#41: while the status cache holds, the working copy's diff is
6312
/// rendered from the stored working-copy change, and says exactly what a
6313
/// snapshot's diff says.
6314
#[test]
6315
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
6316
    hermetic();
6317
    let dir = tempfile::tempdir().unwrap();
6318
    let root = dir.path();
6319
    let repo = Repo::init(root).unwrap();
6320
    write(root, "a.txt", b"one\ntwo\nthree\n");
6321
    write(root, "gone.txt", b"bye\n");
6322
    repo.commit("base", &[]).unwrap();
6323
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
6324
    write(root, "new.txt", b"hello\n");
6325
    fs::remove_file(root.join("gone.txt")).unwrap();
6326
    let snap = repo.snapshot_status("oxy status").unwrap();
6327
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
6328
    assert!(
6329
        repo.status_by_manifest().unwrap().is_some(),
6330
        "the cache holds"
6331
    );
6332
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6333
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
6334
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
6335
}
6336
6337
/// oxygen#41: a manifest written from a walk keeps every directory's time;
6338
/// while none has moved, the check stats the tracked files without listing
6339
/// the tree, and a file added or removed anywhere moves its directory's
6340
/// time, so the tree is listed again.
6341
#[test]
6342
fn the_manifest_check_skips_listing_while_no_directory_changed() {
6343
    hermetic();
6344
    let dir = tempfile::tempdir().unwrap();
6345
    let root = dir.path();
6346
    let repo = Repo::init(root).unwrap();
6347
    write(root, "a.txt", b"a\n");
6348
    write(root, "sub/deep/b.txt", b"b\n");
6349
    repo.commit("base", &[]).unwrap();
6350
    // Out of the racy window: every file and directory a minute old.
6351
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6352
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
6353
        fs::File::open(root.join(p))
6354
            .unwrap()
6355
            .set_modified(old)
6356
            .unwrap();
6357
    }
6358
    repo.snapshot_status("oxy status").unwrap();
6359
    repo.write_manifest(false, false).unwrap();
6360
    let m = repo.read_manifest().unwrap().unwrap().2;
6361
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
6362
    assert_eq!(
6363
        repo.disk_differs_by_dirs(&m),
6364
        Some(false),
6365
        "no listing needed"
6366
    );
6367
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6368
6369
    // A same-size edit with a new time: found by its stat.
6370
    write(root, "sub/deep/b.txt", b"c\n");
6371
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
6372
    write(root, "sub/deep/b.txt", b"b\n");
6373
    fs::File::open(root.join("sub/deep/b.txt"))
6374
        .unwrap()
6375
        .set_modified(old)
6376
        .unwrap();
6377
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
6378
6379
    // A new file moves its directory's time: the tree must be listed.
6380
    write(root, "sub/deep/new.txt", b"n\n");
6381
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6382
    assert_eq!(repo.status_by_manifest().unwrap(), None);
6383
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
6384
    // A removed one too.
6385
    fs::remove_file(root.join("a.txt")).unwrap();
6386
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6387
}
6388
6389
/// oxygen#41: a commit right after a status takes the snapshot the status
6390
/// left (the status cache holds) rather than walking again, and commits
6391
/// exactly what a snapshot would have.
6392
#[test]
6393
fn a_commit_after_a_status_uses_the_cached_snapshot() {
6394
    hermetic();
6395
    let dir = tempfile::tempdir().unwrap();
6396
    let root = dir.path();
6397
    let repo = Repo::init(root).unwrap();
6398
    write(root, "a.txt", b"a\nb\n");
6399
    write(root, ".oxyattributes", b"*.bin binary\n");
6400
    repo.commit("base", &[]).unwrap();
6401
    write(root, "a.txt", b"a\nB\n");
6402
    write(root, "new.txt", b"new\n");
6403
    let snap = repo.snapshot_status("oxy status").unwrap();
6404
    let cached = repo
6405
        .snapshot_from_cache()
6406
        .unwrap()
6407
        .expect("the cache holds");
6408
    assert_eq!(cached.wc_hash, snap.wc_hash);
6409
    assert_eq!(cached.statuses, snap.statuses);
6410
    assert!(
6411
        !cached.attributes.is_empty(),
6412
        "the .oxyattributes file was read"
6413
    );
6414
    let h = repo.commit("edit", &[]).unwrap();
6415
    let c = repo.store().get_change(&h).unwrap();
6416
    assert_eq!(
6417
        c.tree_ops.len() + c.edits.len(),
6418
        snap.wc.tree_ops.len() + snap.wc.edits.len()
6419
    );
6420
    assert_eq!(
6421
        repo.status_by_manifest().unwrap(),
6422
        Some(vec![]),
6423
        "clean after the commit"
6424
    );
6425
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
6426
}
6427
6428
/// oxygen#41: a clean check that verified racy entries restamps the
6429
/// manifest, so later checks can trust them, and a same-size rewrite
6430
/// straight afterwards is still found: entries within two seconds of the
6431
/// new time stay racy.
6432
#[test]
6433
fn a_verified_clean_check_restamps_the_manifest_safely() {
6434
    hermetic();
6435
    let dir = tempfile::tempdir().unwrap();
6436
    let root = dir.path();
6437
    let repo = Repo::init(root).unwrap();
6438
    write(root, "a.txt", b"one\n");
6439
    repo.commit("one", &[]).unwrap();
6440
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
6441
    assert!(repo.clean_by_manifest().unwrap());
6442
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
6443
    assert!(after > before, "restamped");
6444
    write(root, "a.txt", b"two\n");
6445
    assert!(
6446
        !repo.clean_by_manifest().unwrap(),
6447
        "a same-size rewrite is still seen"
6448
    );
6449
}
6450
6451
/// oxygen#35: a history-only state keeps no inserted text. It reads a
6452
/// stored insert's text blob only when it builds that file's graph, and
6453
/// builds the same graph a full load does.
6454
#[test]
6455
fn history_only_states_read_text_only_for_the_graphs_they_build() {
6456
    hermetic();
6457
    let dir = tempfile::tempdir().unwrap();
6458
    let root = dir.path();
6459
    let repo = Repo::init(root).unwrap();
6460
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
6461
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
6462
    write(root, "big.txt", big.as_bytes());
6463
    write(root, "other.txt", other.as_bytes());
6464
    let h = repo.commit("two large files", &[]).unwrap();
6465
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
6466
    let h2 = repo.commit("append", &[]).unwrap();
6467
6468
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
6469
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
6470
        FileContent::Text { bytes, .. } => bytes.clone(),
6471
        other => panic!("{other:?}"),
6472
    };
6473
    // Built on demand, every graph renders as the full load's.
6474
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6475
    let big_node = full.files["big.txt"].node;
6476
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
6477
    repo.load_all_graphs(&mut hist).unwrap();
6478
    let rendered = hist.materialize();
6479
    for p in ["big.txt", "other.txt"] {
6480
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
6481
    }
6482
6483
    // Without other.txt's text blob, history still loads and big.txt still
6484
    // builds: nothing read the other text.
6485
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6486
    assert_eq!(texts.len(), 2);
6487
    let content = |r: &ObjectRef| -> Vec<u8> {
6488
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
6489
        blob.chunks
6490
            .iter()
6491
            .flat_map(|c| repo.store().get(c).unwrap().1)
6492
            .collect()
6493
    };
6494
    let other_text = texts
6495
        .iter()
6496
        .filter_map(|t| match t {
6497
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
6498
            _ => None,
6499
        })
6500
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
6501
        .unwrap();
6502
    repo.store().remove_loose_for_test(&other_text).unwrap();
6503
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6504
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
6505
    assert!(repo
6506
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
6507
        .is_err());
6508
}
6509
6510
/// oxygen#35: the first status after a commit read and rendered every
6511
/// file (79 s and more than 14 GB on the Linux tree), because the
6512
/// manifest had no graph keys for files the commit added.
6513
#[test]
6514
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
6515
    use std::os::unix::fs::PermissionsExt;
6516
    hermetic();
6517
    let dir = tempfile::tempdir().unwrap();
6518
    let root = dir.path();
6519
    let repo = Repo::init(root).unwrap();
6520
    let files = ["a.txt", "b.txt", "d/c.txt"];
6521
    for p in files {
6522
        write(root, p, format!("{p}\n").as_bytes());
6523
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6524
        fs::File::options()
6525
            .write(true)
6526
            .open(root.join(p))
6527
            .unwrap()
6528
            .set_modified(old)
6529
            .unwrap();
6530
    }
6531
    repo.commit("added", &[]).unwrap();
6532
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6533
    assert!(
6534
        m.entries.values().all(|e| e.graph.is_some()),
6535
        "keys recorded at commit"
6536
    );
6537
    // Unreadable files prove the next status reads none of them.
6538
    for p in files {
6539
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
6540
    }
6541
    let snap = repo.snapshot_status("status").unwrap();
6542
    for p in files {
6543
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
6544
    }
6545
    assert!(!snap.changed && snap.statuses.is_empty());
6546
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
6547
}
6548
6549
/// oxygen#35: a checkout reads, renders and writes only the files whose
6550
/// graphs differ, and renders the rest a batch at a time.
6551
#[test]
6552
fn checkout_touches_only_what_differs_and_renders_in_batches() {
6553
    use std::os::unix::fs::PermissionsExt;
6554
    hermetic();
6555
    let dir = tempfile::tempdir().unwrap();
6556
    let root = dir.path();
6557
    let origin = root.join("origin");
6558
    let mut repo = Repo::init(&origin).unwrap();
6559
    // More files than one batch holds.
6560
    let n = 2100;
6561
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6562
    for i in 0..n {
6563
        let p = format!("f/{i:04}.txt");
6564
        write(&origin, &p, format!("file {i}\n").as_bytes());
6565
        fs::File::options()
6566
            .write(true)
6567
            .open(origin.join(&p))
6568
            .unwrap()
6569
            .set_modified(old)
6570
            .unwrap();
6571
    }
6572
    repo.commit("many", &[]).unwrap();
6573
    repo.bookmark_create("feature", None).unwrap();
6574
    repo.bookmark_switch("feature", false).unwrap();
6575
    write(&origin, "f/0007.txt", b"changed\n");
6576
    repo.commit("one change", &[]).unwrap();
6577
6578
    // Switching back to main must not read the unchanged files.
6579
    for i in 0..n {
6580
        if i != 7 {
6581
            let p = origin.join(format!("f/{i:04}.txt"));
6582
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
6583
        }
6584
    }
6585
    let r = repo.bookmark_switch("main", false).unwrap();
6586
    for i in 0..n {
6587
        let p = origin.join(format!("f/{i:04}.txt"));
6588
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
6589
    }
6590
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
6591
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
6592
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6593
6594
    // A clone renders every file, across batches.
6595
    let c = root.join("clone");
6596
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
6597
    for i in [0, 2047, 2048, n - 1] {
6598
        assert_eq!(
6599
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
6600
            format!("file {i}\n").as_bytes()
6601
        );
6602
    }
6603
    let cloned = Repo::open(&c).unwrap();
6604
    assert!(cloned
6605
        .snapshot_status("status")
6606
        .unwrap()
6607
        .statuses
6608
        .is_empty());
6609
}
6610
6611
/// A file written just before the manifest (inside the racy window) is
6612
/// checked by its hash: trusted when equal, caught when edited in place
6613
/// with the same size and time.
6614
#[test]
6615
fn a_racy_manifest_entry_is_checked_by_hash() {
6616
    hermetic();
6617
    let dir = tempfile::tempdir().unwrap();
6618
    let root = dir.path();
6619
    let repo = Repo::init(root).unwrap();
6620
    write(root, "a.txt", b"one\n");
6621
    repo.commit("fresh", &[]).unwrap();
6622
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
6623
    let t = fs::metadata(root.join("a.txt"))
6624
        .unwrap()
6625
        .modified()
6626
        .unwrap();
6627
    write(root, "a.txt", b"two\n");
6628
    fs::File::options()
6629
        .write(true)
6630
        .open(root.join("a.txt"))
6631
        .unwrap()
6632
        .set_modified(t)
6633
        .unwrap();
6634
    assert!(
6635
        !repo.clean_by_manifest().unwrap(),
6636
        "same size and time, other bytes"
6637
    );
6638
    assert_eq!(
6639
        statuses(&repo.snapshot_status("status").unwrap()),
6640
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
6641
    );
6642
}
6643
6644
/// A fetch on one machine moves changes as stored, text blobs among the
6645
/// objects; a change whose text blob did not come is refused, not stored.
6646
#[test]
6647
fn a_raw_bundle_without_a_changes_text_is_refused() {
6648
    hermetic();
6649
    let dir = tempfile::tempdir().unwrap();
6650
    let root = dir.path();
6651
    let a = Repo::init(&root.join("a")).unwrap();
6652
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6653
    write(&root.join("a"), "big.txt", big.as_bytes());
6654
    let h = a.commit("big", &[]).unwrap();
6655
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
6656
    assert_eq!(bundle.raw_changes.len(), 1);
6657
    assert!(bundle.changes.is_empty());
6658
    let b = Repo::init(&root.join("b")).unwrap();
6659
    let mut without = bundle.clone();
6660
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
6661
    let e = b.import_bundle(&without, false).unwrap_err();
6662
    assert!(e.to_string().contains("came without its text blob"), "{e}");
6663
    assert!(!b.store().has(&h));
6664
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
6665
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
6666
}
6667
6668
/// oxygen#30 (vscode): a directory deleted in one line of history and made
6669
/// again was a second node for one Git path, so a file moved into it on
6670
/// another line, where the first node still stood, ended up in two places.
6671
/// An import now brings the directory back rather than make a new one.
6672
#[test]
6673
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
6674
    hermetic();
6675
    if std::process::Command::new("git")
6676
        .arg("--version")
6677
        .output()
6678
        .is_err()
6679
    {
6680
        eprintln!("git not installed; skipping");
6681
        return;
6682
    }
6683
    let dir = tempfile::tempdir().unwrap();
6684
    let root = dir.path();
6685
    let g = root.join("src.git");
6686
    fs::create_dir_all(&g).unwrap();
6687
    let git = |args: &[&str]| -> String {
6688
        let out = std::process::Command::new("git")
6689
            .arg("-C")
6690
            .arg(&g)
6691
            .args([
6692
                "-c",
6693
                "user.name=Grace",
6694
                "-c",
6695
                "[email protected]",
6696
                "-c",
6697
                "commit.gpgsign=false",
6698
            ])
6699
            .args(args)
6700
            .output()
6701
            .unwrap();
6702
        assert!(
6703
            out.status.success(),
6704
            "git {args:?}: {}",
6705
            String::from_utf8_lossy(&out.stderr)
6706
        );
6707
        String::from_utf8_lossy(&out.stdout).trim().to_string()
6708
    };
6709
    git(&["init", "-q", "-b", "main"]);
6710
    write(&g, "d/a.txt", b"a\n");
6711
    write(&g, "c/x.txt", b"x\n");
6712
    git(&["add", "."]);
6713
    git(&["commit", "-qm", "base"]);
6714
    // One line: move x into d while d still stands.
6715
    git(&["checkout", "-qb", "side"]);
6716
    git(&["mv", "c/x.txt", "d/x.txt"]);
6717
    git(&["commit", "-qm", "x into d"]);
6718
    // The other: d goes, comes back, and x moves into it too.
6719
    git(&["checkout", "-q", "main"]);
6720
    git(&["rm", "-q", "d/a.txt"]);
6721
    git(&["commit", "-qm", "d goes"]);
6722
    write(&g, "d/b.txt", b"b\n");
6723
    git(&["add", "."]);
6724
    git(&["commit", "-qm", "d comes back"]);
6725
    git(&["mv", "c/x.txt", "d/x.txt"]);
6726
    git(&["commit", "-qm", "x into d again"]);
6727
    git(&["merge", "-q", "--no-edit", "side"]);
6728
6729
    let repo = Repo::init(&root.join("o")).unwrap();
6730
    repo.import_git(&g, "main").unwrap();
6731
    let v = repo.verify_git_import(&g, "main").unwrap();
6732
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6733
    let st = repo
6734
        .load_state_history(&repo.bookmark_heads().unwrap())
6735
        .unwrap();
6736
    let view = st.tree().view();
6737
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6738
    // The directory is the one the first commit made.
6739
    // Commits made in one second tie on time: find the first by its message.
6740
    let first = repo
6741
        .log()
6742
        .unwrap()
6743
        .into_iter()
6744
        .find(|e| e.change.message.starts_with("base"))
6745
        .unwrap();
6746
    let base = repo
6747
        .load_state_history(&[first.hash])
6748
        .unwrap()
6749
        .tree()
6750
        .view();
6751
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
6752
}
6753
6754
/// oxygen#30, the rest: a placement left under a directory another line
6755
/// removed is out of sight, so no diff reaches it; the merge that settles
6756
/// where the file is retires it.
6757
#[test]
6758
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
6759
    hermetic();
6760
    if std::process::Command::new("git")
6761
        .arg("--version")
6762
        .output()
6763
        .is_err()
6764
    {
6765
        eprintln!("git not installed; skipping");
6766
        return;
6767
    }
6768
    let dir = tempfile::tempdir().unwrap();
6769
    let root = dir.path();
6770
    let g = root.join("src.git");
6771
    fs::create_dir_all(&g).unwrap();
6772
    let run = |args: &[&str]| {
6773
        std::process::Command::new("git")
6774
            .arg("-C")
6775
            .arg(&g)
6776
            .args([
6777
                "-c",
6778
                "user.name=Grace",
6779
                "-c",
6780
                "[email protected]",
6781
                "-c",
6782
                "commit.gpgsign=false",
6783
            ])
6784
            .args(args)
6785
            .output()
6786
            .unwrap()
6787
    };
6788
    let git = |args: &[&str]| {
6789
        let out = run(args);
6790
        assert!(
6791
            out.status.success(),
6792
            "git {args:?}: {}",
6793
            String::from_utf8_lossy(&out.stderr)
6794
        );
6795
    };
6796
    git(&["init", "-q", "-b", "main"]);
6797
    write(&g, "c/x.txt", b"x\n");
6798
    write(&g, "keep.txt", b"k\n");
6799
    git(&["add", "."]);
6800
    git(&["commit", "-qm", "base"]);
6801
    // One line renames the file within c; the other moves it out of c,
6802
    // which goes.
6803
    git(&["checkout", "-qb", "side"]);
6804
    git(&["mv", "c/x.txt", "c/y.txt"]);
6805
    git(&["commit", "-qm", "rename within c"]);
6806
    git(&["checkout", "-q", "main"]);
6807
    fs::create_dir_all(g.join("n")).unwrap();
6808
    git(&["mv", "c/x.txt", "n/x.txt"]);
6809
    git(&["commit", "-qm", "move out of c"]);
6810
    // Git cannot merge the two renames; the merge keeps n/x.txt.
6811
    let _ = run(&["merge", "-q", "side"]);
6812
    let _ = run(&[
6813
        "rm",
6814
        "-q",
6815
        "--cached",
6816
        "--ignore-unmatch",
6817
        "c/y.txt",
6818
        "c/x.txt",
6819
    ]);
6820
    let _ = std::fs::remove_dir_all(g.join("c"));
6821
    write(&g, "n/x.txt", b"x\n");
6822
    git(&["add", "-A"]);
6823
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
6824
6825
    let repo = Repo::init(&root.join("o")).unwrap();
6826
    repo.import_git(&g, "main").unwrap();
6827
    let v = repo.verify_git_import(&g, "main").unwrap();
6828
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6829
    let st = repo
6830
        .load_state_history(&repo.bookmark_heads().unwrap())
6831
        .unwrap();
6832
    let view = st.tree().view();
6833
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6834
    assert!(view.entries.contains_key("n/x.txt"));
6835
}
6836
6837
/// oxygen#30, orphans: a file added on one line into a directory the other
6838
/// line removed is placed where the tree cannot show it; Git's merge keeps
6839
/// the file, and the import's merge leaves exactly one of it.
6840
#[test]
6841
fn git_import_merge_leaves_no_orphan_behind() {
6842
    hermetic();
6843
    if std::process::Command::new("git")
6844
        .arg("--version")
6845
        .output()
6846
        .is_err()
6847
    {
6848
        eprintln!("git not installed; skipping");
6849
        return;
6850
    }
6851
    let dir = tempfile::tempdir().unwrap();
6852
    let root = dir.path();
6853
    let g = root.join("src.git");
6854
    fs::create_dir_all(&g).unwrap();
6855
    let git = |args: &[&str]| {
6856
        let out = std::process::Command::new("git")
6857
            .arg("-C")
6858
            .arg(&g)
6859
            .args([
6860
                "-c",
6861
                "user.name=Grace",
6862
                "-c",
6863
                "[email protected]",
6864
                "-c",
6865
                "commit.gpgsign=false",
6866
            ])
6867
            .args(args)
6868
            .output()
6869
            .unwrap();
6870
        assert!(
6871
            out.status.success(),
6872
            "git {args:?}: {}",
6873
            String::from_utf8_lossy(&out.stderr)
6874
        );
6875
    };
6876
    git(&["init", "-q", "-b", "main"]);
6877
    write(&g, "d/f.txt", b"f\n");
6878
    write(&g, "keep.txt", b"k\n");
6879
    git(&["add", "."]);
6880
    git(&["commit", "-qm", "base"]);
6881
    git(&["checkout", "-qb", "side"]);
6882
    write(&g, "d/new.txt", b"new\n");
6883
    git(&["add", "."]);
6884
    git(&["commit", "-qm", "add into d"]);
6885
    git(&["checkout", "-q", "main"]);
6886
    git(&["rm", "-q", "d/f.txt"]);
6887
    git(&["commit", "-qm", "d goes"]);
6888
    git(&["merge", "-q", "--no-edit", "side"]);
6889
6890
    let repo = Repo::init(&root.join("o")).unwrap();
6891
    repo.import_git(&g, "main").unwrap();
6892
    let v = repo.verify_git_import(&g, "main").unwrap();
6893
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6894
    let st = repo
6895
        .load_state_history(&repo.bookmark_heads().unwrap())
6896
        .unwrap();
6897
    let view = st.tree().view();
6898
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6899
    assert!(view.entries.contains_key("d/new.txt"));
6900
}
6901
6902
/// fsck checks a change's text as the blobs it is stored in, without
6903
/// decoding it: a missing text blob is an error named for the change.
6904
#[test]
6905
fn fsck_names_a_missing_text_blob() {
6906
    hermetic();
6907
    let dir = tempfile::tempdir().unwrap();
6908
    let root = dir.path();
6909
    let repo = Repo::init(root).unwrap();
6910
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6911
    write(root, "big.txt", big.as_bytes());
6912
    let h = repo.commit("big", &[]).unwrap();
6913
    assert_eq!(repo.fsck().unwrap().errors(), 0);
6914
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6915
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
6916
        panic!("a stored text")
6917
    };
6918
    repo.store().remove_loose_for_test(&b).unwrap();
6919
    let rep = repo.fsck().unwrap();
6920
    assert!(rep.errors() > 0);
6921
    assert!(
6922
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
6923
        "{:?}",
6924
        rep.problems
6925
    );
6926
}
6927
6928
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
6929
/// reached with that remote's token and CA (a private subrepo then clones
6930
/// for anyone who can read the parent); another hub gets none of them.
6931
#[test]
6932
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
6933
    hermetic();
6934
    let dir = tempfile::tempdir().unwrap();
6935
    let mut repo = Repo::init(dir.path()).unwrap();
6936
    repo.config
6937
        .set(
6938
            "remote.origin.url",
6939
            "https://Hub.example:7343/doomsdayone/metalgear",
6940
        )
6941
        .unwrap();
6942
    repo.config.set("remote.origin.token", "secret").unwrap();
6943
    repo.config
6944
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
6945
        .unwrap();
6946
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
6947
    assert_eq!(same.token.as_deref(), Some("secret"));
6948
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
6949
    for other in [
6950
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
6951
        "https://hub.example/doomsdayone/rstar-api",
6952
        "http://hub.example:7343/doomsdayone/rstar-api",
6953
    ] {
6954
        let o = repo.credentials_for(other);
6955
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
6956
    }
6957
}
6958
6959
/// oxygen#47: a remote with no token of its own uses the user's credential
6960
/// store for its hub, and a nested checkout finds its parent's remote
6961
/// token there instead of keeping a copy.
6962
#[test]
6963
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
6964
    hermetic();
6965
    let home = tempfile::tempdir().unwrap();
6966
    let dir = tempfile::tempdir().unwrap();
6967
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
6968
    parent
6969
        .config
6970
        .set("remote.origin.url", "https://hub.example/o/parent")
6971
        .unwrap();
6972
    parent.save_config().unwrap();
6973
    assert_eq!(parent.remote_options("origin").token, None);
6974
    crate::credentials::Credentials::at(home.path())
6975
        .save("https://hub.example", "stored", Some("andy"), None)
6976
        .unwrap();
6977
    assert_eq!(
6978
        parent.remote_options("origin").token.as_deref(),
6979
        Some("stored")
6980
    );
6981
6982
    let empty_home = tempfile::tempdir().unwrap();
6983
    let nested = dir.path().join("deps").join("child");
6984
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
6985
    child
6986
        .config
6987
        .set("remote.origin.url", "https://hub.example/o/child")
6988
        .unwrap();
6989
    child.save_config().unwrap();
6990
    assert_eq!(child.remote_options("origin").token, None);
6991
    parent
6992
        .config
6993
        .set("remote.origin.token", "checkout")
6994
        .unwrap();
6995
    parent.save_config().unwrap();
6996
    assert_eq!(
6997
        child.remote_options("origin").token.as_deref(),
6998
        Some("checkout")
6999
    );
7000
    // Another hub's checkout token is not borrowed.
7001
    child
7002
        .config
7003
        .set("remote.origin.url", "https://other.example/o/child")
7004
        .unwrap();
7005
    assert_eq!(child.remote_options("origin").token, None);
7006
}
7007
7008
#[test]
7009
fn the_metadata_cache_survives_a_torn_tail() {
7010
    hermetic();
7011
    let dir = tempfile::tempdir().unwrap();
7012
    let root = dir.path();
7013
    let repo = Repo::init(root).unwrap();
7014
    write(root, "a.txt", b"1\n");
7015
    let h = repo.commit("first", &[]).unwrap();
7016
    let meta = repo.store().get_change_meta(&h).unwrap();
7017
    let cache = repo.store().dir().join("metas");
7018
    let len = fs::metadata(&cache).unwrap().len();
7019
    assert!(len > 0, "a change read is cached");
7020
    // A torn record at the end: the cache reads up to it and cuts it off.
7021
    fs::OpenOptions::new()
7022
        .append(true)
7023
        .open(&cache)
7024
        .unwrap()
7025
        .write_all(&[7; 20])
7026
        .unwrap();
7027
    let again = Repo::open(root).unwrap();
7028
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
7029
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
7030
}
7031
7032
#[test]
7033
fn a_manifest_that_does_not_check_reads_as_none() {
7034
    hermetic();
7035
    let dir = tempfile::tempdir().unwrap();
7036
    let root = dir.path();
7037
    let repo = Repo::init(root).unwrap();
7038
    write(root, "a.txt", b"1\n");
7039
    repo.commit("first", &[]).unwrap();
7040
    let path = repo.manifest_path();
7041
    let mut bytes = fs::read(&path).unwrap();
7042
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
7043
    let last = bytes.len() - 1;
7044
    bytes[last] ^= 1;
7045
    fs::write(&path, &bytes).unwrap();
7046
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
7047
    // The next status reads the files and writes it again.
7048
    let again = Repo::open(root).unwrap();
7049
    assert!(!again.snapshot("status").unwrap().changed);
7050
    assert!(again.read_manifest().unwrap().is_some());
7051
}
7052
7053
#[test]
7054
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
7055
    hermetic();
7056
    let dir = tempfile::tempdir().unwrap();
7057
    let root = dir.path();
7058
    let repo = Repo::init(root).unwrap();
7059
    write(root, "a.txt", b"1\n");
7060
    write(root, "b.txt", b"2\n");
7061
    // b.txt outside the racy window, so snapshots take it as unchanged.
7062
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7063
    fs::File::options()
7064
        .write(true)
7065
        .open(root.join("b.txt"))
7066
        .unwrap()
7067
        .set_modified(old)
7068
        .unwrap();
7069
    repo.commit("first", &[]).unwrap();
7070
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
7071
    repo.snapshot_status("status").unwrap();
7072
    write(root, "a.txt", b"1\n2\n");
7073
    repo.commit("second", &[]).unwrap();
7074
    assert!(
7075
        repo.clean_by_manifest().unwrap(),
7076
        "after a commit of one file"
7077
    );
7078
    // Edited, seen by a status, edited again, then committed: the status
7079
    // left the first edit's stat, which the commit must not keep.
7080
    write(root, "a.txt", b"1\n2\n3\n");
7081
    repo.snapshot_status("status").unwrap();
7082
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
7083
    repo.commit("third", &[]).unwrap();
7084
    assert!(
7085
        repo.clean_by_manifest().unwrap(),
7086
        "after an edit a status saw"
7087
    );
7088
}
7089
7090
#[test]
7091
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
7092
    hermetic();
7093
    let dir = tempfile::tempdir().unwrap();
7094
    let root = dir.path();
7095
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7096
    write(root, "a.txt", b"1\n2\n");
7097
    let a = repo.commit("A", &[]).unwrap();
7098
    repo.bookmark_create("develop", Some(&[a])).unwrap();
7099
    write(root, "a.txt", b"1\nX\n");
7100
    let c = repo.commit("C: 2 to X", &[]).unwrap();
7101
    repo.bookmark_switch("develop", false).unwrap();
7102
    write(root, "a.txt", b"1\nY\n");
7103
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
7104
    repo.bookmark_switch("main", false).unwrap();
7105
7106
    let err = repo.rebase(&c, &[d]).unwrap_err();
7107
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
7108
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
7109
    assert!(r.changed && r.checked_out);
7110
    let snap = repo.snapshot_status("status").unwrap();
7111
    assert!(
7112
        snap.base_snapshot.is_conflicted(),
7113
        "the conflict is in the working copy"
7114
    );
7115
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
7116
    assert!(text.contains('X') && text.contains('Y'), "{text}");
7117
7118
    write(root, "a.txt", b"1\nXY\n");
7119
    repo.commit("Resolve", &[]).unwrap();
7120
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
7121
    assert!(st.contains(&c) && st.contains(&d));
7122
    let files = st.materialize().files;
7123
    assert!(!files["a.txt"].is_conflicted());
7124
    assert!(
7125
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
7126
    );
7127
7128
    // A change the current bookmark does not hold is refused.
7129
    repo.bookmark_switch("develop", false).unwrap();
7130
    write(root, "b.txt", b"b\n");
7131
    let e = repo.commit("E", &[]).unwrap();
7132
    repo.bookmark_switch("main", false).unwrap();
7133
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
7134
    assert!(
7135
        err.to_string().contains("not on the current bookmark"),
7136
        "{err}"
7137
    );
7138
}
7139
7140
#[test]
7141
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
7142
    hermetic();
7143
    let dir = tempfile::tempdir().unwrap();
7144
    let root = dir.path();
7145
    let repo = Repo::init(root).unwrap();
7146
    write(root, "a.txt", b"a\n");
7147
    write(root, "kept.log", b"tracked\n");
7148
    repo.commit("first", &[]).unwrap();
7149
    write(root, "build.log", b"made\n");
7150
    let snap = repo.snapshot_status("status").unwrap();
7151
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
7152
    // A rule written afterwards leaves the added file out again, while the
7153
    // committed one stays tracked.
7154
    write(root, ".gitignore", b"*.log\n");
7155
    let snap = repo.snapshot_status("status").unwrap();
7156
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
7157
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
7158
    write(root, "kept.log", b"tracked, edited\n");
7159
    let snap = repo.snapshot_status("status").unwrap();
7160
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
7161
}
7162
7163
#[test]
7164
fn shed_graphs_come_back_the_same() {
7165
    hermetic();
7166
    let dir = tempfile::tempdir().unwrap();
7167
    let root = dir.path();
7168
    let repo = Repo::init(root).unwrap();
7169
    write(root, "a.txt", b"1\n2\n3\n");
7170
    write(root, "b.txt", b"x\n");
7171
    repo.commit("first", &[]).unwrap();
7172
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
7173
    repo.commit("second", &[]).unwrap();
7174
    let heads = repo.bookmark_heads().unwrap();
7175
    let mut st = repo.load_state_history(&heads).unwrap();
7176
    let view = st.tree().view();
7177
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
7178
        .iter()
7179
        .map(|p| view.entries[*p].node)
7180
        .collect();
7181
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7182
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7183
    assert_eq!(st.built_count(), 2);
7184
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
7185
    assert_eq!((shed, st.built_count()), (2, 0));
7186
    // A later change applies on top of the shed history.
7187
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
7188
    let h3 = repo.commit("third", &[]).unwrap();
7189
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
7190
    st.add_known(h3, skeleton, texts);
7191
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7192
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7193
    assert_eq!(after[1], before[1]);
7194
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
7195
}
7196
7197
#[test]
7198
fn many_edited_files_diff_in_parallel() {
7199
    // Enough edited files that the builder diffs them in parallel; the
7200
    // commit must hold exactly what is on disk, and a second snapshot
7201
    // must find nothing left to commit.
7202
    hermetic();
7203
    let dir = tempfile::tempdir().unwrap();
7204
    let root = dir.path();
7205
    let repo = Repo::init(root).unwrap();
7206
    let text = |i: usize, round: usize| {
7207
        let mut s = String::new();
7208
        for line in 0..50 {
7209
            if round > 0 && line % 7 == i % 7 {
7210
                s.push_str(&format!("edited {round} {i} {line}\n"));
7211
            } else {
7212
                s.push_str(&format!("file {i} line {line}\n"));
7213
            }
7214
        }
7215
        if round > 0 && i.is_multiple_of(3) {
7216
            s.push_str("appended\n");
7217
        }
7218
        s
7219
    };
7220
    for i in 0..40 {
7221
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
7222
    }
7223
    repo.commit("first", &[]).unwrap();
7224
    for i in 0..40 {
7225
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
7226
    }
7227
    let h = repo.commit("edit every file", &[]).unwrap();
7228
    let snap = repo.load_state(&[h]).unwrap().materialize();
7229
    for i in 0..40 {
7230
        let want = text(i, 1);
7231
        assert!(
7232
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
7233
            "d/f{i}.txt as committed"
7234
        );
7235
    }
7236
    assert!(
7237
        repo.commit("nothing", &[]).is_err(),
7238
        "nothing left to commit"
7239
    );
7240
}
7241
7242
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
7243
/// is known (fetch printed "up to date" while main was behind), a change
7244
/// only fetched resolves and says where it is, and a checkout whose only
7245
/// remote is not `origin` uses that one.
7246
#[test]
7247
fn a_fetched_change_shows_as_behind_and_resolves() {
7248
    hermetic();
7249
    let dir = tempfile::tempdir().unwrap();
7250
    let root = dir.path();
7251
    let origin = Repo::init(&root.join("origin")).unwrap();
7252
    drop(origin);
7253
    let url = root.join("origin").to_string_lossy().to_string();
7254
    let a = Repo::clone(&url, &root.join("a"))
7255
        .unwrap()
7256
        .with_home(root.join("home-a"));
7257
    write(&root.join("a"), "f.txt", b"one\n");
7258
    a.commit("one", &[]).unwrap();
7259
    a.push("origin", false).unwrap();
7260
    let b = Repo::clone(&url, &root.join("b"))
7261
        .unwrap()
7262
        .with_home(root.join("home-b"));
7263
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7264
7265
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
7266
    let h2 = a.commit("two", &[]).unwrap();
7267
    a.push("origin", false).unwrap();
7268
    b.fetch("origin").unwrap();
7269
    // Fetched, not pulled: one behind, the change found and placed.
7270
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7271
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
7272
    assert_eq!(
7273
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
7274
            .unwrap(),
7275
        h2
7276
    );
7277
    assert_eq!(
7278
        b.remote_only_location(&h2).unwrap().as_deref(),
7279
        Some("origin/main")
7280
    );
7281
    // Fetching again changes nothing: still behind, which is what the
7282
    // CLI now says rather than "up to date".
7283
    b.fetch("origin").unwrap();
7284
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7285
    b.pull("origin").unwrap();
7286
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7287
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
7288
7289
    // One remote, not called origin: it is the default.
7290
    let mut c = Repo::init(&root.join("c")).unwrap();
7291
    assert_eq!(c.default_remote(), "origin");
7292
    c.config.set("remote.earth.url", &url).unwrap();
7293
    assert_eq!(c.default_remote(), "earth");
7294
    c.config.set("remote.origin.url", &url).unwrap();
7295
    assert_eq!(c.default_remote(), "origin");
7296
}
7297
7298
/// oxygen#57: a clone from a relative local path records the remote as an
7299
/// absolute path, so fetch still finds it from inside the clone.
7300
#[test]
7301
fn a_clone_from_a_relative_path_records_it_absolute() {
7302
    hermetic();
7303
    let dir = tempfile::tempdir().unwrap();
7304
    let root = dir.path();
7305
    Repo::init(&root.join("origin")).unwrap();
7306
    let rel = crate::protocol::stored_url("relative/repo");
7307
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
7308
    assert_eq!(
7309
        crate::protocol::stored_url("https://hub.example/o/n"),
7310
        "https://hub.example/o/n"
7311
    );
7312
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
7313
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
7314
    // A bucket is kept as written: it is not a path.
7315
    assert_eq!(
7316
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
7317
        "s3://bucket/prefix?profile=p"
7318
    );
7319
    let url = root.join("origin").to_string_lossy().to_string();
7320
    let b = Repo::clone(&url, &root.join("b")).unwrap();
7321
    assert_eq!(b.config.remotes["origin"], url);
7322
    b.fetch("origin").unwrap();
7323
}
7324
7325
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
7326
/// and gets its subrepos at their pins from this workspace's copies, with
7327
/// their remotes pointing where the subrepos come from.
7328
#[test]
7329
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
7330
    hermetic();
7331
    let dir = tempfile::tempdir().unwrap();
7332
    let root = dir.path();
7333
    Repo::init(&root.join("lib-origin")).unwrap();
7334
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7335
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7336
        .unwrap()
7337
        .with_home(root.join("home"));
7338
    write(&root.join("lib"), "lib.txt", b"v1\n");
7339
    let l1 = lib.commit("lib v1", &[]).unwrap();
7340
    assert!(lib.push("origin", false).unwrap()[0].ok);
7341
7342
    let app_dir = root.join("app");
7343
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7344
    write(&app_dir, "main.txt", b"app\n");
7345
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7346
    app.commit("app with lib", &[]).unwrap();
7347
    // A second bookmark, and the main workspace on another.
7348
    app.bookmark_create("develop", None).unwrap();
7349
    app.bookmark_create("feature", None).unwrap();
7350
    let mut app = app;
7351
    app.bookmark_switch("feature", false).unwrap();
7352
    assert_eq!(app.config.bookmark, "feature");
7353
7354
    // The library's origin goes away: the subrepo must come from here.
7355
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
7356
    let heads = app.resolve_heads("develop").unwrap();
7357
    let ws = app
7358
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
7359
        .unwrap();
7360
    assert_eq!(
7361
        ws.config.bookmark, "develop",
7362
        "the new workspace is on develop"
7363
    );
7364
    assert_eq!(
7365
        app.config.bookmark, "feature",
7366
        "and this one stays on its own"
7367
    );
7368
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
7369
    assert_eq!(
7370
        sub.config.remotes["origin"], lib_url,
7371
        "its origin is the subrepo's URL"
7372
    );
7373
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
7374
    assert_eq!(
7375
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
7376
        b"v1\n"
7377
    );
7378
}
7379
7380
/// Revsets (docs/revset_query_language.md): symbols, relations, set
7381
/// operators and the predicates, over a small graph with two heads and
7382
/// a rename.
7383
#[test]
7384
fn revsets_select_changes_by_relation_author_text_date_and_path() {
7385
    hermetic();
7386
    let dir = tempfile::tempdir().unwrap();
7387
    let root = dir.path();
7388
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7389
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
7390
        .unwrap();
7391
    write(root, "src/a.rs", b"one\n");
7392
    let a = repo.commit("first: add a", &[]).unwrap();
7393
    write(root, "src/a.rs", b"one\ntwo\n");
7394
    let b = repo.commit("second: grow a", &[]).unwrap();
7395
    // A second head, independent of b: a new file on top of a.
7396
    repo.checkout(&[a], false, "checkout a").unwrap();
7397
    write(root, "docs/notes.md", b"notes\n");
7398
    let c = repo.commit("third: notes", &[]).unwrap();
7399
    // Back to both heads, then rename a.rs: the node keeps its identity.
7400
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
7401
        .unwrap();
7402
    fs::remove_file(root.join("src/a.rs")).unwrap();
7403
    write(root, "src/z.rs", b"one\ntwo\n");
7404
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
7405
    let wc = repo.working_copy().unwrap().0;
7406
    // A saved revset is checked when set.
7407
    repo.set_user_config("revset.mine", "author(me) & ::main")
7408
        .unwrap();
7409
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
7410
    let set = |src: &str| -> Vec<ChangeHash> {
7411
        let mut v = repo.revset(src).unwrap().hashes;
7412
        v.sort();
7413
        v
7414
    };
7415
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
7416
        let mut v = hs.to_vec();
7417
        v.sort();
7418
        v
7419
    };
7420
7421
    // Changes commute: a new file depends on nothing and the rename on the
7422
    // file's creation, so the graph is a, b->a, d->a, c, and the working
7423
    // copy on the three heads b, c, d.
7424
    let heads = sorted(&repo.bookmark_heads().unwrap());
7425
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
7426
    assert!(heads.contains(&d) && heads.contains(&c));
7427
    // Symbols and closures.
7428
    assert_eq!(set("main"), heads);
7429
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
7430
    assert_eq!(set("@"), vec![wc]);
7431
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
7432
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
7433
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
7434
    assert_eq!(
7435
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
7436
        sorted(&[a, b])
7437
    );
7438
    // Ranges: what main has beyond b, and `..` forms.
7439
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
7440
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
7441
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
7442
    // Operators and precedence: ~ binds tighter than &, & than |.
7443
    assert_eq!(
7444
        set(&format!("::main ~ #{}", d.short(12))),
7445
        sorted(&[a, b, c])
7446
    );
7447
    assert_eq!(
7448
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
7449
        sorted(&[b, c])
7450
    );
7451
    assert_eq!(set("all() ~ ::main"), vec![wc]);
7452
    // Relations.
7453
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
7454
    head_deps.sort();
7455
    head_deps.dedup();
7456
    assert_eq!(set("deps(main)"), head_deps);
7457
    let on_a: Vec<ChangeHash> = [b, c, d]
7458
        .into_iter()
7459
        .filter(|h| meta(h).deps.contains(&a))
7460
        .collect();
7461
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
7462
    assert_eq!(set("heads(::main)"), heads);
7463
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
7464
    assert_eq!(
7465
        set(&format!(
7466
            "heads(#{} | #{} | #{})",
7467
            a.short(12),
7468
            b.short(12),
7469
            c.short(12)
7470
        )),
7471
        sorted(&[b, c])
7472
    );
7473
    assert_eq!(set("latest(::main, 1)"), vec![d]);
7474
    assert_eq!(set("kind(working-copy)"), vec![wc]);
7475
    assert_eq!(set("none()"), vec![]);
7476
    // Predicates: author by name, email, key prefix and `me`.
7477
    let key = repo.config.author_key.unwrap();
7478
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
7479
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
7480
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
7481
    assert_eq!(set("author(me) & ::main").len(), 4);
7482
    assert_eq!(set("author(nobody)"), vec![]);
7483
    assert_eq!(set("description(notes)"), vec![c]);
7484
    assert_eq!(set("description(\"rename a\")"), vec![d]);
7485
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
7486
    assert_eq!(set("date(..2000-01-01)"), vec![]);
7487
    // touches follows the node through the rename, in the current state.
7488
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
7489
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
7490
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
7491
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
7492
    // Newest first in the result order.
7493
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
7494
    // The saved revset, and errors that say what is wrong.
7495
    assert_eq!(set("mine()").len(), 4);
7496
    let e = repo.revset("nosuch()").unwrap_err().to_string();
7497
    assert!(e.contains("unknown function nosuch()"), "{e}");
7498
    let e = repo.revset("main &").unwrap_err().to_string();
7499
    assert!(e.contains("at character"), "{e}");
7500
    let e = repo.revset("zzzz").unwrap_err().to_string();
7501
    assert!(e.contains("no change matches"), "{e}");
7502
    let e = repo
7503
        .revset_with_budget("::main", std::time::Duration::ZERO)
7504
        .unwrap_err()
7505
        .to_string();
7506
    assert!(e.contains("budget"), "{e}");
7507
    // The log entries carry the bookmark's heads and the working copy.
7508
    let entries = repo.log_revset("::@").unwrap();
7509
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
7510
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
7511
    // push); then a signed change, a tag, and a revocation.
7512
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
7513
    assert_eq!(set("signed_by(me)"), vec![]);
7514
    repo.sign_change(&d).unwrap();
7515
    assert_eq!(set("signed_by(me)"), vec![d]);
7516
    assert_eq!(set("signed_by([email protected])"), vec![d]);
7517
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
7518
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
7519
    assert_eq!(set("delegated()"), vec![]);
7520
    assert_eq!(set("revoked()"), vec![]);
7521
    assert_eq!(set("attested(tag)"), vec![]);
7522
    repo.tag_create("v1", &[b], "first").unwrap();
7523
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
7524
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
7525
    assert_eq!(set("attested(receipt)"), vec![]);
7526
    assert_eq!(set("built(test)"), vec![]);
7527
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
7528
    assert!(e.contains("tag, receipt or ref"), "{e}");
7529
    repo.revoke_identity(&key, "test").unwrap();
7530
    assert_eq!(set("revoked()"), vec![d]);
7531
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
7532
}
7533
7534
#[test]
7535
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
7536
    let dir = tempfile::tempdir().unwrap();
7537
    let root = dir.path();
7538
    let home = root.join("home");
7539
    // Ada's identity lives in the user file; repository `a` pins the same
7540
    // key in its own file, repository `b` names none.
7541
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
7542
    let (key, _) = a
7543
        .create_identity("Ada", "[email protected]", IdentityScope::User)
7544
        .unwrap();
7545
    a.config.set("author.key", &key.to_hex()).unwrap();
7546
    a.save_config().unwrap();
7547
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
7548
    let r = a
7549
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
7550
        .unwrap();
7551
    assert_eq!(
7552
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
7553
        r.new.to_hex(),
7554
        "the user file follows"
7555
    );
7556
    assert_eq!(
7557
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
7558
        r.new.to_hex(),
7559
        "the pinning repository follows"
7560
    );
7561
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
7562
    assert_eq!(
7563
        b.config.author_key,
7564
        Some(r.new),
7565
        "a checkout without a pin follows the user file"
7566
    );
7567
    // A repository-scoped identity leaves the user file alone.
7568
    let other_home = root.join("home2");
7569
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
7570
    let (ck, _) = c
7571
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
7572
        .unwrap();
7573
    assert!(!other_home.join("config.toml").exists());
7574
    let r2 = c.rotate_identity().unwrap();
7575
    assert_ne!(r2.new, ck);
7576
    assert_eq!(
7577
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
7578
        r2.new.to_hex()
7579
    );
7580
    assert!(
7581
        !other_home.join("config.toml").exists(),
7582
        "a repository-scoped identity stays repository-scoped"
7583
    );
7584
    // Several delegates in one rotation; a repeat is refused.
7585
    let (d1, d2) = (
7586
        SecretKey::generate().identity("D1", "d1@x", 1),
7587
        SecretKey::generate().identity("D2", "d2@x", 1),
7588
    );
7589
    let r3 = c
7590
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
7591
        .unwrap();
7592
    assert_eq!(r3.identity.delegates.len(), 2);
7593
    assert!(c
7594
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
7595
        .is_err());
7596
}
7597
7598
/// Two unrelated histories that both add the same file, joined by two
7599
/// independent merges on two branches, then those branches merged: Git
7600
/// merges identical additions cleanly, and the import must too (#71,
7601
/// found in VS Code's history).
7602
#[test]
7603
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
7604
    // Batches of one: every merge renders apart from the state, where a
7605
    // file whose graph the state had built came out empty (#71).
7606
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7607
    hermetic();
7608
    if std::process::Command::new("git")
7609
        .arg("--version")
7610
        .output()
7611
        .is_err()
7612
    {
7613
        eprintln!("git not installed; skipping");
7614
        return;
7615
    }
7616
    let dir = tempfile::tempdir().unwrap();
7617
    let root = dir.path();
7618
    let g = root.join("src.git");
7619
    fs::create_dir_all(&g).unwrap();
7620
    let git = |args: &[&str]| -> String {
7621
        let out = std::process::Command::new("git")
7622
            .arg("-C")
7623
            .arg(&g)
7624
            .args([
7625
                "-c",
7626
                "user.name=Grace",
7627
                "-c",
7628
                "[email protected]",
7629
                "-c",
7630
                "commit.gpgsign=false",
7631
            ])
7632
            .args(args)
7633
            .output()
7634
            .unwrap();
7635
        assert!(
7636
            out.status.success(),
7637
            "git {args:?}: {}",
7638
            String::from_utf8_lossy(&out.stderr)
7639
        );
7640
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7641
    };
7642
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
7643
    // History A: main.
7644
    git(&["init", "-q", "-b", "main"]);
7645
    write(&g, "gulpfile.js", text);
7646
    write(&g, "a.txt", b"a\n");
7647
    git(&["add", "."]);
7648
    git(&["commit", "-q", "-m", "A root"]);
7649
    // History B: an unrelated root adding the same file, identical.
7650
    git(&["checkout", "-q", "--orphan", "fork"]);
7651
    git(&["rm", "-q", "-r", "--cached", "."]);
7652
    for f in ["gulpfile.js", "a.txt"] {
7653
        let _ = fs::remove_file(g.join(f));
7654
    }
7655
    write(&g, "gulpfile.js", text);
7656
    write(&g, "b.txt", b"b\n");
7657
    git(&["add", "."]);
7658
    git(&["commit", "-q", "-m", "B root"]);
7659
    // Two branches from main, each joining B on its own.
7660
    git(&["checkout", "-q", "-b", "one", "main"]);
7661
    git(&[
7662
        "merge",
7663
        "-q",
7664
        "--no-ff",
7665
        "--allow-unrelated-histories",
7666
        "-m",
7667
        "join on one",
7668
        "fork",
7669
    ]);
7670
    git(&["checkout", "-q", "-b", "two", "main"]);
7671
    write(&g, "a.txt", b"a\ntwo\n");
7672
    git(&["commit", "-q", "-am", "work on two"]);
7673
    git(&[
7674
        "merge",
7675
        "-q",
7676
        "--no-ff",
7677
        "--allow-unrelated-histories",
7678
        "-m",
7679
        "join on two",
7680
        "fork",
7681
    ]);
7682
    // Then the two joins meet, and the file is reformatted after.
7683
    git(&["checkout", "-q", "main"]);
7684
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
7685
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7686
    write(
7687
        &g,
7688
        "gulpfile.js",
7689
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
7690
    );
7691
    git(&["commit", "-q", "-am", "after"]);
7692
7693
    let dest = root.join("dest");
7694
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7695
    repo.import_git(&g, "main").unwrap();
7696
    let v = repo.verify_git_import(&g, "main").unwrap();
7697
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7698
    assert_eq!(
7699
        fs::read(dest.join("gulpfile.js")).unwrap(),
7700
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
7701
    );
7702
}
7703
7704
/// As above, but the two joins keep different copies (each branch had a
7705
/// different version when it joined), and later work edits each copy:
7706
/// the shape of VS Code's c67ef57cda90 (#71).
7707
#[test]
7708
fn git_import_joins_where_each_join_kept_a_different_copy() {
7709
    // Batches of one: every merge renders apart from the state, where a
7710
    // file whose graph the state had built came out empty (#71).
7711
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7712
    hermetic();
7713
    if std::process::Command::new("git")
7714
        .arg("--version")
7715
        .output()
7716
        .is_err()
7717
    {
7718
        eprintln!("git not installed; skipping");
7719
        return;
7720
    }
7721
    let dir = tempfile::tempdir().unwrap();
7722
    let root = dir.path();
7723
    let g = root.join("src.git");
7724
    fs::create_dir_all(&g).unwrap();
7725
    let run = |args: &[&str]| {
7726
        std::process::Command::new("git")
7727
            .arg("-C")
7728
            .arg(&g)
7729
            .args([
7730
                "-c",
7731
                "user.name=Grace",
7732
                "-c",
7733
                "[email protected]",
7734
                "-c",
7735
                "commit.gpgsign=false",
7736
            ])
7737
            .args(args)
7738
            .output()
7739
            .unwrap()
7740
    };
7741
    let git = |args: &[&str]| -> String {
7742
        let out = run(args);
7743
        assert!(
7744
            out.status.success(),
7745
            "git {args:?}: {}",
7746
            String::from_utf8_lossy(&out.stderr)
7747
        );
7748
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7749
    };
7750
    git(&["init", "-q", "-b", "main"]);
7751
    write(
7752
        &g,
7753
        "gulpfile.js",
7754
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
7755
    );
7756
    git(&["add", "."]);
7757
    git(&["commit", "-q", "-m", "A root"]);
7758
    write(
7759
        &g,
7760
        "gulpfile.js",
7761
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
7762
    );
7763
    git(&["commit", "-q", "-am", "whitespace"]);
7764
    git(&["checkout", "-q", "--orphan", "fork"]);
7765
    git(&["rm", "-q", "-r", "--cached", "."]);
7766
    let _ = fs::remove_file(g.join("gulpfile.js"));
7767
    write(
7768
        &g,
7769
        "gulpfile.js",
7770
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
7771
    );
7772
    git(&["add", "."]);
7773
    git(&["commit", "-q", "-m", "B root"]);
7774
    // Branch one joins B keeping main's copy; branch two keeps B's.
7775
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
7776
        git(&["checkout", "-q", "-b", branch, "main"]);
7777
        let _ = run(&[
7778
            "merge",
7779
            "-q",
7780
            "--no-ff",
7781
            "--allow-unrelated-histories",
7782
            "-m",
7783
            "join",
7784
            "fork",
7785
        ]);
7786
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
7787
        git(&["add", "gulpfile.js"]);
7788
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
7789
    }
7790
    // Each branch then edits its copy.
7791
    git(&["checkout", "-q", "one"]);
7792
    write(
7793
        &g,
7794
        "gulpfile.js",
7795
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
7796
    );
7797
    git(&["commit", "-q", "-am", "tslint on one"]);
7798
    git(&["checkout", "-q", "two"]);
7799
    write(
7800
        &g,
7801
        "gulpfile.js",
7802
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
7803
    );
7804
    write(&g, "extra.txt", b"x\n");
7805
    write(&g, "more.txt", b"m\n");
7806
    git(&["add", "."]);
7807
    git(&["commit", "-q", "-am", "fmt on two"]);
7808
    // They meet: resolved by hand.
7809
    git(&["checkout", "-q", "one"]);
7810
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7811
    write(
7812
        &g,
7813
        "gulpfile.js",
7814
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
7815
    );
7816
    git(&["add", "gulpfile.js"]);
7817
    git(&["commit", "-q", "-m", "merge two into one"]);
7818
7819
    let dest = root.join("dest");
7820
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7821
    repo.import_git(&g, "one").unwrap();
7822
    let v = repo.verify_git_import(&g, "one").unwrap();
7823
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7824
}
7825
7826
/// oxygen#68: on a store that is not this disk's directory, the operation
7827
/// head is the store's reference record, moved by compare-and-swap. Two
7828
/// handles recording from the same head both get through, merged; a swap
7829
/// from a stale version is refused; a second repository cannot start on a
7830
/// store that already holds one.
7831
#[test]
7832
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
7833
    use crate::strata::{MemoryStore, Store as _};
7834
    let backend = std::sync::Arc::new(MemoryStore::new());
7835
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
7836
    let dir = tempfile::tempdir().unwrap();
7837
    let a = Repo::init(dir.path()).unwrap();
7838
    assert!(
7839
        !dir.path().join(".oxy/ops/head").exists(),
7840
        "the head is not a file"
7841
    );
7842
    let (h0, op0) = a.head_op().unwrap();
7843
    let record = backend
7844
        .read_ref(HEAD_RECORD)
7845
        .unwrap()
7846
        .expect("the head is the store's record");
7847
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
7848
7849
    let b = Repo::open(dir.path()).unwrap();
7850
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
7851
    let mut va = op0.view.clone();
7852
    va.bookmarks.insert("from-a".into(), state);
7853
    let mut vb = op0.view.clone();
7854
    vb.bookmarks.insert("from-b".into(), state);
7855
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
7856
    assert_eq!(b.head_ref().unwrap(), rb);
7857
    // a recorded from h0 too: the head moved, so the two are merged.
7858
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
7859
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
7860
    assert_eq!(head, ra);
7861
    assert!(
7862
        op.command.ends_with("(merged with a concurrent operation)"),
7863
        "{}",
7864
        op.command
7865
    );
7866
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
7867
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
7868
7869
    // A swap from a version that is no longer current moves nothing.
7870
    let (h, v) = a.read_head().unwrap();
7871
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
7872
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
7873
    assert_eq!(a.head_ref().unwrap(), rb);
7874
7875
    let other = tempfile::tempdir().unwrap();
7876
    let err = Repo::init(other.path())
7877
        .err()
7878
        .expect("the store already holds a log")
7879
        .to_string();
7880
    assert!(
7881
        err.contains("already holds a repository's operation log"),
7882
        "{err}"
7883
    );
7884
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
7885
}
7886
7887
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
7888
/// objects and operation head there, with `.oxy/cache` in front: it works
7889
/// as one on disk does, reopens, and survives losing its cache.
7890
#[test]
7891
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
7892
    hermetic();
7893
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
7894
        return;
7895
    }
7896
    let dir = tempfile::tempdir().unwrap();
7897
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
7898
    let url = format!("dir://{}", bucket.display());
7899
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
7900
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
7901
    write(&root, "a.txt", b"one\n");
7902
    let h1 = repo.commit("First", &[]).unwrap();
7903
    write(&root, "a.txt", b"one\ntwo\n");
7904
    let h2 = repo.commit("Second", &[]).unwrap();
7905
    assert!(
7906
        !root.join(".oxy/ops/head").exists(),
7907
        "the head is in the store"
7908
    );
7909
    assert!(bucket.join("ops/head").is_file());
7910
    assert!(root.join(".oxy/cache").is_dir());
7911
    drop(repo);
7912
7913
    // Reopened, and again with no cache at all: everything comes from the store.
7914
    for drop_cache in [false, true] {
7915
        if drop_cache {
7916
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
7917
        }
7918
        let repo = Repo::open(&root).unwrap();
7919
        let log: Vec<String> = repo
7920
            .op_log()
7921
            .unwrap()
7922
            .into_iter()
7923
            .map(|(_, op)| op.command)
7924
            .collect();
7925
        assert!(log.len() >= 3, "{log:?}");
7926
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
7927
        let heads = repo
7928
            .store()
7929
            .get_state(&repo.view().unwrap().bookmarks["main"])
7930
            .unwrap()
7931
            .heads;
7932
        assert_eq!(heads, vec![h2]);
7933
        assert_eq!(
7934
            repo.load_state(&heads).unwrap().materialize().files.len(),
7935
            1
7936
        );
7937
    }
7938
7939
    // A second repository cannot start on the same store.
7940
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
7941
        .err()
7942
        .unwrap()
7943
        .to_string();
7944
    assert!(
7945
        err.contains("already holds a repository's operation log"),
7946
        "{err}"
7947
    );
7948
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
7949
        .err()
7950
        .unwrap()
7951
        .to_string();
7952
    assert!(err.contains("cannot open that kind of store"), "{err}");
7953
}
7954
7955
/// oxygen#75: the prompt's quick check agrees with status in a repository
7956
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
7957
/// another state, clean again once that pin is committed. (It compared the
7958
/// subrepo's directory as if it were a file, so it was always dirty.)
7959
#[test]
7960
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
7961
    hermetic();
7962
    let dir = tempfile::tempdir().unwrap();
7963
    let root = dir.path();
7964
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
7965
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7966
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7967
        .unwrap()
7968
        .with_home(root.join("home"));
7969
    write(&root.join("lib"), "lib.txt", b"v1\n");
7970
    lib.commit("lib v1", &[]).unwrap();
7971
    assert!(lib.push("origin", false).unwrap()[0].ok);
7972
    let app_dir = root.join("app");
7973
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7974
    write(&app_dir, "main.txt", b"app\n");
7975
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7976
    app.commit("app with lib", &[]).unwrap();
7977
    // Out of the racy window, so the stat-only path decides.
7978
    std::thread::sleep(std::time::Duration::from_millis(2100));
7979
    let reopen = || Repo::open(&app_dir).unwrap();
7980
    assert_eq!(
7981
        reopen().quick_dirty().unwrap(),
7982
        Some(false),
7983
        "clean, as status says"
7984
    );
7985
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
7986
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
7987
    nested.commit("lib v2", &[]).unwrap();
7988
    assert_eq!(
7989
        reopen().quick_dirty().unwrap(),
7990
        Some(true),
7991
        "the subrepo moved"
7992
    );
7993
    reopen().commit("pin lib v2", &[]).unwrap();
7994
    std::thread::sleep(std::time::Duration::from_millis(2100));
7995
    assert_eq!(
7996
        reopen().quick_dirty().unwrap(),
7997
        Some(false),
7998
        "the new pin is committed"
7999
    );
8000
}
8001
8002
#[test]
8003
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
8004
    // oxygen#72: a .oxymodules section with no subrepo behind it.
8005
    hermetic();
8006
    let dir = tempfile::tempdir().unwrap();
8007
    let root = dir.path();
8008
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8009
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8010
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8011
        .unwrap()
8012
        .with_home(root.join("home"));
8013
    write(&root.join("lib"), "lib.txt", b"v1\n");
8014
    lib.commit("lib v1", &[]).unwrap();
8015
    assert!(lib.push("origin", false).unwrap()[0].ok);
8016
    let app_dir = root.join("app");
8017
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8018
    write(
8019
        &app_dir,
8020
        ".oxymodules",
8021
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
8022
    );
8023
    let unpinned = app.unpinned_modules().unwrap();
8024
    assert_eq!(unpinned.len(), 1);
8025
    assert_eq!(unpinned[0].0, "libs/lib");
8026
    assert_eq!(unpinned[0].1.url, lib_url);
8027
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
8028
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8029
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
8030
}
8031
8032
#[test]
8033
fn the_bookmark_revset_function_names_only_bookmarks() {
8034
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
8035
    hermetic();
8036
    let dir = tempfile::tempdir().unwrap();
8037
    let repo = Repo::init(dir.path()).unwrap();
8038
    write(dir.path(), "a.txt", b"a\n");
8039
    let a = repo.commit("A", &[]).unwrap();
8040
    write(dir.path(), "b.txt", b"b\n");
8041
    let b = repo.commit("B", &[]).unwrap();
8042
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
8043
    heads.sort();
8044
    let mut want = repo.bookmark_heads().unwrap();
8045
    want.sort();
8046
    assert_eq!(heads, want);
8047
    assert!(heads.contains(&b));
8048
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
8049
    // A change prefix is a symbol, not a bookmark.
8050
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
8051
    assert!(repo.revset(&prefix).is_ok());
8052
    let e = repo
8053
        .revset(&format!("bookmark({prefix})"))
8054
        .unwrap_err()
8055
        .to_string();
8056
    assert!(e.contains("no such bookmark"), "{e}");
8057
}
8058
8059
#[test]
8060
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
8061
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
8062
    // pinning the subrepo, and the nested repository on disk at that pin.
8063
    hermetic();
8064
    let dir = tempfile::tempdir().unwrap();
8065
    let root = dir.path();
8066
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8067
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8068
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8069
        .unwrap()
8070
        .with_home(root.join("home"));
8071
    write(&root.join("lib"), "lib.txt", b"v1\n");
8072
    lib.commit("lib v1", &[]).unwrap();
8073
    assert!(lib.push("origin", false).unwrap()[0].ok);
8074
    let app_dir = root.join("app");
8075
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8076
    write(&app_dir, "main.txt", b"app\n");
8077
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8078
    // The stale state: registered in .oxymodules, never pinned.
8079
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
8080
    app.commit("initial", &[]).unwrap();
8081
    let stale = app.bookmark_heads().unwrap();
8082
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
8083
    app.commit("pin lib", &[]).unwrap();
8084
    let newer = app.bookmark_heads().unwrap();
8085
    app.checkout(&stale, false, "test").unwrap();
8086
    write(&app_dir, "notes.txt", b"mine\n");
8087
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
8088
    assert_eq!(carried, vec!["notes.txt".to_string()]);
8089
    assert!(app_dir.join("notes.txt").exists());
8090
}
8091
8092
#[test]
8093
fn a_bookmark_only_behind_its_remote_catches_up() {
8094
    // oxygen#74: switch takes the remote's state rather than a stale one.
8095
    hermetic();
8096
    let dir = tempfile::tempdir().unwrap();
8097
    let root = dir.path();
8098
    let _origin = Repo::init(&root.join("origin")).unwrap();
8099
    let url = root.join("origin").to_string_lossy().to_string();
8100
    let one = Repo::clone(&url, &root.join("one"))
8101
        .unwrap()
8102
        .with_home(root.join("home"));
8103
    write(&root.join("one"), "a.txt", b"a\n");
8104
    one.commit("A", &[]).unwrap();
8105
    assert!(one.push("origin", false).unwrap()[0].ok);
8106
    let two = Repo::clone(&url, &root.join("two"))
8107
        .unwrap()
8108
        .with_home(root.join("home"));
8109
    write(&root.join("two"), "b.txt", b"b\n");
8110
    two.commit("B", &[]).unwrap();
8111
    assert!(two.push("origin", false).unwrap()[0].ok);
8112
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
8113
    one.fetch("origin").unwrap();
8114
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
8115
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
8116
    // Local work the remote lacks: left alone.
8117
    write(&root.join("one"), "c.txt", b"c\n");
8118
    one.commit("C", &[]).unwrap();
8119
    write(&root.join("two"), "d.txt", b"d\n");
8120
    two.commit("D", &[]).unwrap();
8121
    assert!(two.push("origin", false).unwrap()[0].ok);
8122
    one.fetch("origin").unwrap();
8123
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
8124
}
8125
8126
#[test]
8127
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
8128
    // oxygen#83: remotes earth and gcs, origin removed.
8129
    hermetic();
8130
    let dir = tempfile::tempdir().unwrap();
8131
    let root = dir.path();
8132
    let _up = Repo::init(&root.join("up")).unwrap();
8133
    let url = root.join("up").to_string_lossy().to_string();
8134
    let other = Repo::clone(&url, &root.join("other"))
8135
        .unwrap()
8136
        .with_home(root.join("home"));
8137
    write(&root.join("other"), "a.txt", b"a\n");
8138
    other.commit("a", &[]).unwrap();
8139
    assert!(other.push("origin", false).unwrap()[0].ok);
8140
    let mut one = Repo::clone(&url, &root.join("one"))
8141
        .unwrap()
8142
        .with_home(root.join("home"));
8143
    one.config.set("remote.earth.url", &url).unwrap();
8144
    one.config.set("remote.gcs.url", &url).unwrap();
8145
    one.config.set("remote.origin.url", "").unwrap();
8146
    one.save_config().unwrap();
8147
    write(&root.join("other"), "b.txt", b"b\n");
8148
    other.commit("b", &[]).unwrap();
8149
    assert!(other.push("origin", false).unwrap()[0].ok);
8150
    one.fetch("earth").unwrap();
8151
    let b = one
8152
        .bookmarks()
8153
        .unwrap()
8154
        .into_iter()
8155
        .find(|b| b.name == "main")
8156
        .unwrap();
8157
    assert_eq!(
8158
        (b.remote.as_deref(), b.behind),
8159
        (Some("earth"), Some(1)),
8160
        "a stale origin copy is not used"
8161
    );
8162
    assert_eq!(
8163
        one.default_remote(),
8164
        "origin",
8165
        "no default chosen among several"
8166
    );
8167
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
8168
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
8169
    one.config.set("core.remote", "earth").unwrap();
8170
    assert_eq!(one.default_remote(), "earth");
8171
}
8172
8173
#[test]
8174
fn a_missing_author_identity_says_how_to_fix_it() {
8175
    // oxygen#82: an agent home's author.key naming an identity the
8176
    // repository does not hold.
8177
    hermetic();
8178
    let dir = tempfile::tempdir().unwrap();
8179
    let mut repo = Repo::init(dir.path()).unwrap();
8180
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
8181
    repo.config.set("author.key", &missing.to_hex()).unwrap();
8182
    let e = repo.identity(&missing).unwrap_err().to_string();
8183
    assert!(
8184
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
8185
        "{e}"
8186
    );
8187
    assert!(e.contains("this repository's config"), "{e}");
8188
}
8189
8190
#[test]
8191
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
8192
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
8193
    // the working copy, a pull with nothing new left it there, and status
8194
    // said "clean".
8195
    hermetic();
8196
    let dir = tempfile::tempdir().unwrap();
8197
    let root = dir.path();
8198
    let _up = Repo::init(&root.join("up")).unwrap();
8199
    let url = root.join("up").to_string_lossy().to_string();
8200
    let other = Repo::clone(&url, &root.join("other"))
8201
        .unwrap()
8202
        .with_home(root.join("home"));
8203
    write(&root.join("other"), "a.txt", b"a\n");
8204
    other.commit("a", &[]).unwrap();
8205
    assert!(other.push("origin", false).unwrap()[0].ok);
8206
    let one = Repo::clone(&url, &root.join("one"))
8207
        .unwrap()
8208
        .with_home(root.join("home"));
8209
    write(&root.join("other"), "b.txt", b"b\n");
8210
    other.commit("b", &[]).unwrap();
8211
    assert!(other.push("origin", false).unwrap()[0].ok);
8212
    one.fetch("origin").unwrap();
8213
    // The bookmark moves; the working copy does not.
8214
    let theirs = one.resolve_heads("origin/main").unwrap();
8215
    one.bookmark_set("main", &theirs).unwrap();
8216
    assert!(!root.join("one/b.txt").exists());
8217
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
8218
    let r = one.pull("origin").unwrap();
8219
    assert!(
8220
        !r.changed && r.checked_out,
8221
        "nothing new, but the working copy caught up"
8222
    );
8223
    assert!(root.join("one/b.txt").exists());
8224
    assert_eq!(one.working_copy_behind().unwrap(), None);
8225
}
8226
8227
#[test]
8228
fn touched_nodes_cache_answers_as_the_changes_do() {
8229
    hermetic();
8230
    let dir = tempfile::tempdir().unwrap();
8231
    let repo = Repo::init(dir.path()).unwrap();
8232
    write(dir.path(), "a.txt", b"one\n");
8233
    write(dir.path(), "b.txt", b"x\n");
8234
    repo.snapshot("t").unwrap();
8235
    let c1 = repo.commit("first", &[]).unwrap();
8236
    write(dir.path(), "b.txt", b"y\n");
8237
    repo.snapshot("t").unwrap();
8238
    repo.commit("b only", &[]).unwrap();
8239
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
8240
    write(dir.path(), "c.txt", b"one\ntwo\n");
8241
    repo.snapshot("t").unwrap();
8242
    let c3 = repo.commit("rename and edit", &[]).unwrap();
8243
    // Uncommitted work, so the working copy touches a file too.
8244
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
8245
    repo.snapshot("t").unwrap();
8246
8247
    let path = dir.path().join(".oxy/index/touched");
8248
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
8249
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
8250
    assert!(path.exists(), "the first query writes the cache");
8251
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
8252
    assert_eq!(cold, warm, "the cache answers as the changes do");
8253
    let (wc, _) = repo.working_copy().unwrap();
8254
    assert_eq!(
8255
        cold,
8256
        vec![wc, c3, c1],
8257
        "renames followed, the working copy included"
8258
    );
8259
8260
    // Working-copy changes are not kept: they are replaced by every snapshot.
8261
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
8262
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
8263
    assert!(cached.contains(&c1) && cached.contains(&c3));
8264
8265
    // A damaged cache is ignored, not trusted.
8266
    let mut bytes = fs::read(&path).unwrap();
8267
    let last = bytes.len() - 40;
8268
    bytes[last] ^= 1;
8269
    fs::write(&path, &bytes).unwrap();
8270
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
8271
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
8272
    assert_eq!(hashes(touches), vec![c3, c1]);
8273
}
8274
8275
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
8276
/// file back where it was leave two placements at one place, which the
8277
/// tree shows as one file. Removing it, and then its directory, retires
8278
/// both, so no copy is left under a directory that is gone.
8279
#[test]
8280
fn git_import_removes_every_copy_of_a_file_at_one_place() {
8281
    hermetic();
8282
    if std::process::Command::new("git")
8283
        .arg("--version")
8284
        .output()
8285
        .is_err()
8286
    {
8287
        eprintln!("git not installed; skipping");
8288
        return;
8289
    }
8290
    let dir = tempfile::tempdir().unwrap();
8291
    let root = dir.path();
8292
    let g = root.join("src.git");
8293
    fs::create_dir_all(&g).unwrap();
8294
    let git = |args: &[&str]| {
8295
        let out = std::process::Command::new("git")
8296
            .arg("-C")
8297
            .arg(&g)
8298
            .args([
8299
                "-c",
8300
                "user.name=Grace",
8301
                "-c",
8302
                "[email protected]",
8303
                "-c",
8304
                "commit.gpgsign=false",
8305
            ])
8306
            .args(args)
8307
            .output()
8308
            .unwrap();
8309
        assert!(
8310
            out.status.success(),
8311
            "git {args:?}: {}",
8312
            String::from_utf8_lossy(&out.stderr)
8313
        );
8314
    };
8315
    git(&["init", "-q", "-b", "main"]);
8316
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
8317
    write(&g, "keep.txt", b"k\n");
8318
    git(&["add", "."]);
8319
    git(&["commit", "-qm", "base"]);
8320
    fs::create_dir_all(g.join("d/sub")).unwrap();
8321
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
8322
    git(&["commit", "-qm", "into sub"]);
8323
    git(&["checkout", "-qb", "side"]);
8324
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8325
    git(&["commit", "-qm", "back, on side"]);
8326
    git(&["checkout", "-q", "main"]);
8327
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8328
    git(&["commit", "-qm", "back, on main"]);
8329
    git(&["merge", "-q", "--no-edit", "side"]);
8330
    git(&["rm", "-rq", "d"]);
8331
    git(&["commit", "-qm", "d goes"]);
8332
8333
    let repo = Repo::init(&root.join("o")).unwrap();
8334
    repo.import_git(&g, "main").unwrap();
8335
    let v = repo.verify_git_import(&g, "main").unwrap();
8336
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8337
    let st = repo
8338
        .load_state_history(&repo.bookmark_heads().unwrap())
8339
        .unwrap();
8340
    let view = st.tree().view();
8341
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8342
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
8343
}
8344
8345
/// oxygen#94: a state index's file histories are read, and checked by
8346
/// their own hashes, only when a file is built. One found damaged is an
8347
/// error that says so, the index is removed, and the next read rebuilds it.
8348
#[test]
8349
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
8350
    hermetic();
8351
    let dir = tempfile::tempdir().unwrap();
8352
    let repo = Repo::init(dir.path()).unwrap();
8353
    for i in 0..6 {
8354
        write(
8355
            dir.path(),
8356
            &format!("f{i}.txt"),
8357
            format!("one {i}\n").as_bytes(),
8358
        );
8359
    }
8360
    repo.snapshot("t").unwrap();
8361
    repo.commit("first", &[]).unwrap();
8362
    for i in 0..6 {
8363
        write(
8364
            dir.path(),
8365
            &format!("f{i}.txt"),
8366
            format!("one {i}\ntwo\n").as_bytes(),
8367
        );
8368
    }
8369
    repo.snapshot("t").unwrap();
8370
    repo.commit("second", &[]).unwrap();
8371
    let want: Vec<Vec<u8>> = (0..6)
8372
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
8373
        .collect();
8374
    // The index of the working copy's base, holding every file's history
8375
    // (a few changes behind, an index is replayed onto, not rewritten).
8376
    let (_, wc) = repo.working_copy().unwrap();
8377
    let base = repo.load_state_history(&wc.deps).unwrap();
8378
    repo.write_state_index(&wc.deps, &base);
8379
    for (i, w) in want.iter().enumerate() {
8380
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8381
    }
8382
    let index = repo.state_indexes();
8383
    assert!(!index.is_empty(), "a state index was written");
8384
    // The histories are last in the file: damage the last of them.
8385
    let mut bytes = fs::read(&index[0]).unwrap();
8386
    let last = bytes.len() - 1;
8387
    bytes[last] ^= 0x40;
8388
    fs::write(&index[0], &bytes).unwrap();
8389
8390
    let reads: Vec<_> = (0..6)
8391
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
8392
        .collect();
8393
    let damaged: Vec<String> = reads
8394
        .iter()
8395
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
8396
        .collect();
8397
    assert_eq!(damaged.len(), 1, "{damaged:?}");
8398
    assert!(
8399
        damaged[0].contains("state index was damaged")
8400
            && damaged[0].contains("run the command again"),
8401
        "{}",
8402
        damaged[0]
8403
    );
8404
    // Every file reads right again, from an index rebuilt from history.
8405
    for (i, w) in want.iter().enumerate() {
8406
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8407
    }
8408
}