OXYGENHUB
# 91334b7fa574 oxygen / tests / cli_json.rs
30.5 KiB · Rust · last changed Cylinder C1, first part: artifacts as trees of the repository's chunks, oxy artifact pack/list/show/unpack/verify, kept by gc (refs #108) 7 days ago source blame history raw
c6aa5bd9 Andy McCall ↶ 1
//! Every `--json` output of the CLI parses as JSON and carries the fields
2
//! the VS Code extension relies on (oxygen-vscode/docs/spec.md section 4).
3
4
use serde_json::Value;
5
use std::path::Path;
6
use std::process::Command;
7
8
fn oxy(dir: &Path, home: &Path, args: &[&str]) -> (i32, Vec<u8>, String) {
75167672 Andy McCall 9
    let out = Command::new(env!("CARGO_BIN_EXE_oxy"))
10
        .arg("--plain")
11
        .args(args)
12
        .current_dir(dir)
13
        .env("OXY_HOME", home)
14
        .env("NO_COLOR", "1")
15
        .output()
16
        .unwrap();
17
    (
18
        out.status.code().unwrap_or(-1),
19
        out.stdout,
20
        String::from_utf8_lossy(&out.stderr).to_string(),
21
    )
c6aa5bd9 Andy McCall ↶ 22
}
23
24
fn json(dir: &Path, home: &Path, args: &[&str]) -> Value {
25
    let (code, out, err) = oxy(dir, home, args);
75167672 Andy McCall 26
    assert!(
27
        code == 0 || code == 2 || code == 1,
28
        "oxy {args:?} exited {code}: {err}"
29
    );
30
    serde_json::from_slice(&out).unwrap_or_else(|e| {
31
        panic!(
32
            "oxy {args:?} is not JSON: {e}\n{}",
33
            String::from_utf8_lossy(&out)
34
        )
35
    })
c6aa5bd9 Andy McCall ↶ 36
}
37
38
fn write(dir: &Path, rel: &str, content: &str) {
39
    let p = dir.join(rel);
40
    std::fs::create_dir_all(p.parent().unwrap()).unwrap();
41
    std::fs::write(p, content).unwrap();
42
}
43
44
#[test]
45
fn machine_interface_round_trips() {
46
    let tmp = tempfile::tempdir().unwrap();
47
    let home = tmp.path().join("home");
48
    std::fs::create_dir_all(&home).unwrap();
49
    let origin = tmp.path().join("origin");
75167672 Andy McCall 50
    assert_eq!(
51
        oxy(tmp.path(), &home, &["init", origin.to_str().unwrap()]).0,
52
        0
53
    );
c6aa5bd9 Andy McCall ↶ 54
    let repo = tmp.path().join("repo");
75167672 Andy McCall 55
    assert_eq!(
56
        oxy(
57
            tmp.path(),
58
            &home,
59
            &["clone", origin.to_str().unwrap(), repo.to_str().unwrap()]
60
        )
61
        .0,
62
        0
63
    );
c6aa5bd9 Andy McCall ↶ 64
    let r = repo.as_path();
75167672 Andy McCall 65
    assert_eq!(
66
        oxy(
67
            r,
68
            &home,
69
            &[
70
                "identity",
71
                "create",
72
                "--name",
73
                "Ada",
74
                "--email",
75
                "[email protected]"
76
            ]
77
        )
78
        .0,
79
        0
80
    );
81
    assert_eq!(
82
        oxy(r, &home, &["config", "--user", "core.sign", "change"]).0,
83
        0
84
    );
c6aa5bd9 Andy McCall ↶ 85
86
    let v = json(r, &home, &["version", "--json"]);
87
    assert_eq!(v["protocol"], 1);
88
    let root = json(r, &home, &["root", "--json"]);
89
    assert_eq!(root["bookmark"], "main");
90
    assert!(root["root"].as_str().unwrap().ends_with("repo"));
91
92
    write(r, "a.txt", "1\n2\n3\n");
93
    write(r, "b.txt", "b\n");
94
    let st = json(r, &home, &["status", "--json"]);
95
    assert_eq!(st["paths"].as_array().unwrap().len(), 2);
96
    assert_eq!(oxy(r, &home, &["commit", "-m", "base"]).0, 0);
97
    write(r, "a.txt", "0\n1\n2\n3\n");
98
    write(r, "b.txt", "b\nbb\n");
99
    write(r, "c.txt", "c\n");
100
101
    // diff and hunks agree on the working copy.
102
    let d = json(r, &home, &["diff", "--json"]);
103
    let files = d["files"].as_array().unwrap();
104
    assert_eq!(files.len(), 3, "{d}");
105
    let a = files.iter().find(|f| f["path"] == "a.txt").unwrap();
106
    assert_eq!(a["kind"], "modified");
107
    assert_eq!(a["hunks"][0]["base_line"], 0);
108
    assert_eq!(a["hunks"][0]["added"][0], "0\n");
109
    let c = files.iter().find(|f| f["path"] == "c.txt").unwrap();
110
    assert_eq!(c["kind"], "added");
111
    let hunks = json(r, &home, &["hunks", "--json"]);
112
    let hunks = hunks.as_array().unwrap();
113
    assert!(hunks.len() >= 3, "{hunks:?}");
75167672 Andy McCall 114
    let b_hunk = hunks.iter().find(|h| h["path"] == "b.txt").unwrap()["index"]
115
        .as_u64()
116
        .unwrap();
c6aa5bd9 Andy McCall ↶ 117
    // Commit only b's hunk; discard c by path; then discard a's remaining hunk.
75167672 Andy McCall 118
    assert_eq!(
119
        oxy(
120
            r,
121
            &home,
122
            &["commit", "-m", "b only", "--hunks", &b_hunk.to_string()]
123
        )
124
        .0,
125
        0
126
    );
c6aa5bd9 Andy McCall ↶ 127
    assert_eq!(oxy(r, &home, &["discard", "c.txt"]).0, 0);
128
    assert!(!r.join("c.txt").exists());
129
    let hunks = json(r, &home, &["hunks", "--json"]);
75167672 Andy McCall 130
    let a_hunk = hunks
131
        .as_array()
132
        .unwrap()
133
        .iter()
134
        .find(|h| h["path"] == "a.txt")
135
        .unwrap()["index"]
136
        .as_u64()
137
        .unwrap();
138
    assert_eq!(
139
        oxy(r, &home, &["discard", "--hunks", &a_hunk.to_string()]).0,
140
        0
141
    );
142
    assert_eq!(
143
        std::fs::read_to_string(r.join("a.txt")).unwrap(),
144
        "1\n2\n3\n"
145
    );
c6aa5bd9 Andy McCall ↶ 146
    let st = json(r, &home, &["status", "--json"]);
147
    assert_eq!(st["clean"], true, "{st}");
148
149
    // cat serves file content at states.
150
    let (code, out, _) = oxy(r, &home, &["cat", "b.txt"]);
151
    assert_eq!((code, out.as_slice()), (0, b"b\nbb\n".as_slice()));
152
    let (code, out, _) = oxy(r, &home, &["cat", "b.txt", "-r", "main"]);
153
    assert_eq!((code, out.as_slice()), (0, b"b\nbb\n".as_slice()));
154
155
    // log, show, verify, op log, bookmarks, remotes, sync.
156
    let log = json(r, &home, &["log", "--json"]);
157
    let changes = log["changes"].as_array().unwrap();
158
    assert_eq!(changes.len(), 3, "working copy plus two changes: {log}");
159
    let head = changes.iter().find(|c| c["message"] == "b only").unwrap();
160
    assert_eq!(head["signature"]["status"], "signed");
161
    assert_eq!(head["author"], "Ada");
162
    let hash = head["hash"].as_str().unwrap().to_string();
163
    let by_path = json(r, &home, &["log", "--json", "--path", "b.txt"]);
164
    assert_eq!(by_path["changes"].as_array().unwrap().len(), 2, "{by_path}");
165
    let show = json(r, &home, &["show", "--json", &format!("#{}", &hash[..12])]);
166
    assert_eq!(show["files"][0]["path"], "b.txt");
0299076f Andy McCall ↶ 167
    // oxygen#119: lines added and removed per file, and --stat.
168
    assert!(show["files"][0]["added"].as_u64().unwrap() >= 1, "{show}");
169
    let (code, out, _) = oxy(r, &home, &["show", "--stat", &format!("#{}", &hash[..12])]);
170
    let out = String::from_utf8_lossy(&out);
171
    assert!(
172
        code == 0 && out.contains("b.txt") && out.contains("1 file changed"),
173
        "{out}"
174
    );
175
    assert!(!out.contains("@@"), "the files, not the diff: {out}");
c6aa5bd9 Andy McCall ↶ 176
    let verify = json(r, &home, &["verify", "--json"]);
75167672 Andy McCall 177
    assert!(verify
178
        .as_array()
179
        .unwrap()
180
        .iter()
181
        .all(|v| v["status"] == "signed"));
c6aa5bd9 Andy McCall ↶ 182
    let ops = json(r, &home, &["op", "log", "--json"]);
183
    assert!(ops[0]["current"] == true && ops.as_array().unwrap().len() > 3);
184
    assert_eq!(oxy(r, &home, &["bookmark", "create", "feature"]).0, 0);
185
    let bms = json(r, &home, &["bookmark", "list", "--json"]);
75167672 Andy McCall 186
    assert_eq!(
187
        bms.as_array()
188
            .unwrap()
189
            .iter()
190
            .map(|b| b["name"].as_str().unwrap())
191
            .collect::<Vec<_>>(),
192
        vec!["feature", "main"]
193
    );
c6aa5bd9 Andy McCall ↶ 194
    let remotes = json(r, &home, &["remote", "list", "--json"]);
195
    assert_eq!(remotes[0]["name"], "origin");
196
    let push = json(r, &home, &["push", "--json"]);
197
    assert_eq!(push[0]["ok"], true, "{push}");
198
    let fetch = json(r, &home, &["fetch", "--json"]);
199
    assert_eq!(fetch["remote"], "origin");
200
    let pull = json(r, &home, &["pull", "--json"]);
201
    assert_eq!(pull["changed"], false);
202
    assert_eq!(json(r, &home, &["resolve", "--json"])["conflicted"], false);
75167672 Andy McCall 203
    assert!(json(r, &home, &["submodule", "status", "--json"])
204
        .as_array()
205
        .unwrap()
206
        .is_empty());
c6aa5bd9 Andy McCall ↶ 207
    assert!(json(r, &home, &["bisect", "status", "--json"]).is_null());
208
    assert!(json(r, &home, &["policy", "show", "--json"]).is_null());
209
    assert_eq!(oxy(r, &home, &["policy", "init"]).0, 0);
210
    let policy = json(r, &home, &["policy", "show", "--json"]);
211
    assert_eq!(policy["roots"][0]["name"], "Ada");
3a6effc7 Andy McCall ↶ 212
    // Keyless (oxygenhub#241): a hub's certified subject may sign too.
213
    let hub =
214
        oxy_core::identity::SecretKey::generate().identity("oxygenhub.io", "[email protected]", 1);
215
    let hub_file = r.join("hub.identity");
216
    std::fs::write(&hub_file, hub.encode()).unwrap();
217
    let grant = [
218
        "policy",
219
        "grant-subject",
220
        "repo:ada/demo:bookmark:main",
221
        "--issuer",
222
        hub_file.to_str().unwrap(),
223
        "--scope",
224
        "refs",
225
    ];
226
    assert_eq!(oxy(r, &home, &grant).0, 0);
227
    let policy = json(r, &home, &["policy", "show", "--json"]);
228
    let subjects = &policy["rules"][0]["subjects"][0];
229
    assert_eq!(
230
        (
231
            subjects["subject"].as_str(),
232
            subjects["issuer"]["name"].as_str(),
233
            subjects["scope"].as_str()
234
        ),
235
        (
236
            Some("repo:ada/demo:bookmark:main"),
237
            Some("oxygenhub.io"),
238
            Some("refs")
239
        )
240
    );
241
    std::fs::remove_file(&hub_file).unwrap();
75167672 Andy McCall 242
    assert_eq!(
243
        oxy(r, &home, &["tag", "create", "v1", "-m", "first tag"]).0,
244
        0
245
    );
1196b29b Andy McCall ↶ 246
    let tags = json(r, &home, &["tag", "list", "--json"]);
75167672 Andy McCall 247
    assert_eq!(
248
        (tags[0]["name"].as_str(), tags[0]["message"].as_str()),
249
        (Some("v1"), Some("first tag"))
250
    );
1196b29b Andy McCall ↶ 251
    let ws = json(r, &home, &["workspace", "list", "--json"]);
75167672 Andy McCall 252
    assert_eq!(
253
        (ws.as_array().unwrap().len(), ws[0]["current"].as_bool()),
254
        (1, Some(true))
255
    );
c6aa5bd9 Andy McCall ↶ 256
}
6a81dbab Andy McCall ↶ 257
258
/// `oxy commit -F`, `oxy describe` naming and tags as changes (feedback
259
/// 4 and 6).
642da263 Andy McCall ↶ 260
/// Cylinder C1 (oxygen#108): a directory packs into an artifact of this
261
/// repository's chunks, lists and shows as JSON, survives gc, and unpacks.
262
#[test]
263
fn artifacts_pack_show_survive_gc_and_unpack() {
264
    let tmp = tempfile::tempdir().unwrap();
265
    let home = tmp.path().join("home");
266
    let dir = tmp.path().join("r");
267
    std::fs::create_dir_all(&dir).unwrap();
268
    assert_eq!(oxy(&dir, &home, &["init"]).0, 0);
269
    write(tmp.path(), "out/bin/tool", "#!/bin/sh\necho hi\n");
270
    write(tmp.path(), "out/README", "a tool\n");
271
    let out = tmp.path().join("out");
272
    let pack = [
273
        "artifact",
274
        "pack",
275
        out.to_str().unwrap(),
276
        "--kind",
277
        "package",
278
        "--arch",
279
        "x86_64",
280
        "--label",
281
        "version=0.1.0",
282
        "--json",
283
    ];
284
    let a = json(&dir, &home, &pack);
285
    let name = a["name"].as_str().unwrap().to_string();
286
    assert_eq!(
287
        (
288
            a["kind"].as_str(),
289
            a["files"].as_u64(),
290
            a["labels"]["version"].as_str()
291
        ),
292
        (Some("package"), Some(2), Some("0.1.0"))
293
    );
294
    let list = json(&dir, &home, &["artifact", "list", "--json"]);
295
    assert_eq!(list[0]["name"], name.as_str());
296
    let (code, _, err) = oxy(
297
        &dir,
298
        &home,
299
        &[
300
            "artifact",
301
            "pack",
302
            out.to_str().unwrap(),
303
            "--kind",
304
            "tarball",
305
        ],
306
    );
307
    assert_ne!(code, 0);
308
    assert!(err.contains("runner-image"), "{err}");
309
    assert_eq!(oxy(&dir, &home, &["gc", "--now"]).0, 0);
310
    let (code, verified, err) = oxy(&dir, &home, &["artifact", "verify", &name[..8]]);
311
    assert_eq!(code, 0, "{err}");
312
    assert!(String::from_utf8_lossy(&verified).contains("2 files check out"));
313
    let back = tmp.path().join("back");
314
    assert_eq!(
315
        oxy(
316
            &dir,
317
            &home,
318
            &["artifact", "unpack", &name, back.to_str().unwrap()]
319
        )
320
        .0,
321
        0
322
    );
323
    assert_eq!(
324
        std::fs::read_to_string(back.join("bin/tool")).unwrap(),
325
        "#!/bin/sh\necho hi\n"
326
    );
327
}
328
64dc5197 Andy McCall ↶ 329
/// oxygen#144: a first identity needs no repository; the next repository
330
/// signs as it.
6a81dbab Andy McCall ↶ 331
#[test]
64dc5197 Andy McCall ↶ 332
fn a_first_identity_needs_no_repository() {
333
    let tmp = tempfile::tempdir().unwrap();
334
    let home = tmp.path().join("home");
335
    let nowhere = tmp.path().join("nowhere");
336
    std::fs::create_dir_all(&nowhere).unwrap();
337
    let local = ["identity", "create", "--local"];
338
    let (code, _, err) = oxy(&nowhere, &home, &local);
339
    assert_ne!(code, 0, "--local needs a repository");
340
    assert!(err.contains("no oxy repository"), "{err}");
341
    let ident = [
342
        "identity",
343
        "create",
344
        "--name",
345
        "Ada",
346
        "--email",
347
        "[email protected]",
348
    ];
349
    let (code, out, err) = oxy(&nowhere, &home, &ident);
350
    assert_eq!(code, 0, "{err}");
351
    let out = String::from_utf8_lossy(&out);
352
    assert!(
353
        out.contains("Created identity Ada <[email protected]>"),
354
        "{out}"
355
    );
356
    let user = oxy_core::repo::read_config_file(&home.join("config.toml")).unwrap();
357
    let key = user["author.key"].clone();
358
    assert_eq!(user["author.name"], "Ada");
359
    assert!(home.join("keys").join(format!("{key}.secret")).exists());
360
    assert!(!nowhere.join(".oxy").exists(), "no repository made");
361
362
    // A repository made afterwards signs its changes with it.
363
    let dir = tmp.path().join("r");
364
    std::fs::create_dir_all(&dir).unwrap();
365
    assert_eq!(oxy(&dir, &home, &["init"]).0, 0);
366
    assert_eq!(oxy(&dir, &home, &["config", "core.sign", "change"]).0, 0);
367
    write(&dir, "a.txt", "a\n");
368
    let (code, _, err) = oxy(&dir, &home, &["commit", "-m", "First"]);
369
    assert_eq!(code, 0, "{err}");
370
    let log = json(&dir, &home, &["log", "--json", "-n", "2"]);
371
    let first = &log["changes"][1];
372
    assert_eq!(first["message"], "First");
373
    assert_eq!(first["signature"]["status"], "signed", "{first}");
374
    assert_eq!(first["signature"]["key"], key.as_str());
375
    assert_eq!(first["signature"]["name"], "Ada");
376
}
377
378
#[test]
6a81dbab Andy McCall ↶ 379
fn commit_from_a_file_and_describe_for_builds() {
380
    let tmp = tempfile::tempdir().unwrap();
381
    let home = tmp.path().join("home");
382
    std::fs::create_dir_all(&home).unwrap();
383
    let dir = tmp.path().join("r");
384
    std::fs::create_dir_all(&dir).unwrap();
385
    assert_eq!(oxy(&dir, &home, &["init"]).0, 0);
386
    write(&dir, "a.txt", "a\n");
387
    write(
388
        tmp.path(),
389
        "msg.txt",
390
        "Subject from a file\n\nA body\nof two lines.\n",
391
    );
392
    let msg = tmp.path().join("msg.txt");
393
    let (code, _, err) = oxy(&dir, &home, &["commit", "-F", msg.to_str().unwrap()]);
394
    assert_eq!(code, 0, "{err}");
395
    let log = json(&dir, &home, &["log", "--json", "-n", "2"]);
396
    assert_eq!(
397
        log["changes"][1]["message"],
398
        "Subject from a file\n\nA body\nof two lines."
399
    );
400
    assert_ne!(oxy(&dir, &home, &["commit"]).0, 0, "a message is required");
401
402
    // Untagged: bookmark and change; a tag names it; later work counts.
403
    let d = json(&dir, &home, &["describe", "--json"]);
404
    assert_eq!(
405
        (d["tag"].clone(), d["dirty"].clone()),
406
        (Value::Null, Value::Bool(false))
407
    );
408
    let change = d["change"].as_str().unwrap().to_string();
409
    assert_eq!(d["describe"], format!("main-{}", &change[..8]));
410
    assert_eq!(
411
        oxy(&dir, &home, &["tag", "create", "v0.1.0", "-m", "first"]).0,
412
        0
413
    );
414
    let (_, out, _) = oxy(&dir, &home, &["describe"]);
415
    assert_eq!(String::from_utf8_lossy(&out).trim(), "v0.1.0");
416
    let (code, out, err) = oxy(&dir, &home, &["show", "v0.1.0"]);
417
    assert_eq!(code, 0, "a tag names its change: {err}");
418
    assert!(String::from_utf8_lossy(&out).contains("Subject from a file"));
419
    write(&dir, "b.txt", "b\n");
420
    let d = json(&dir, &home, &["describe", "--json"]);
421
    assert_eq!(d["describe"], "v0.1.0-dirty");
422
    assert_eq!(oxy(&dir, &home, &["commit", "-m", "b"]).0, 0);
423
    write(&dir, "c.txt", "c\n");
424
    assert_eq!(oxy(&dir, &home, &["commit", "-m", "c"]).0, 0);
425
    let d = json(&dir, &home, &["describe", "--json"]);
426
    let change = d["change"].as_str().unwrap();
427
    assert_eq!(d["distance"], 2);
428
    assert_eq!(d["describe"], format!("v0.1.0-2-{}", &change[..8]));
429
}
83d61e80 Andy McCall ↶ 430
431
/// `oxy log -L START,END:PATH`: the history of a range of lines.
432
#[test]
433
fn the_history_of_a_function() {
434
    let tmp = tempfile::tempdir().unwrap();
435
    let home = tmp.path().join("home");
436
    std::fs::create_dir_all(&home).unwrap();
437
    let dir = tmp.path().join("r");
438
    std::fs::create_dir_all(&dir).unwrap();
439
    assert_eq!(oxy(&dir, &home, &["init"]).0, 0);
440
    write(&dir, "f.rs", "use x;\nfn a() {\n  one();\n}\n");
441
    assert_eq!(oxy(&dir, &home, &["commit", "-m", "add f"]).0, 0);
442
    write(&dir, "f.rs", "use y;\nfn a() {\n  one();\n}\n");
443
    assert_eq!(oxy(&dir, &home, &["commit", "-m", "import"]).0, 0);
444
    write(&dir, "f.rs", "use y;\nfn a() {\n  two();\n}\n");
445
    assert_eq!(oxy(&dir, &home, &["commit", "-m", "body"]).0, 0);
446
    let v = json(&dir, &home, &["log", "--json", "-L", "2,4:f.rs"]);
447
    let messages: Vec<&str> = v["changes"]
448
        .as_array()
449
        .unwrap()
450
        .iter()
451
        .map(|c| c["message"].as_str().unwrap())
452
        .collect();
453
    assert_eq!(messages, ["body", "add f"], "not the import");
454
    let (code, _, err) = oxy(&dir, &home, &["log", "-L", "2:f.rs"]);
455
    assert_ne!(code, 0);
456
    assert!(err.contains("START,END:PATH"), "{err}");
457
}
fc1a466a Andy McCall ↶ 458
459
#[test]
460
fn receipts_verify_import_list_show_and_export() {
461
    use oxy_core::hash::{ObjectRef, ObjectType};
462
    use oxy_core::identity::SecretKey;
463
    use oxy_core::objects::StateObject;
464
    use oxy_core::receipt::{Receipt, SignedReceipt};
465
    let tmp = tempfile::tempdir().unwrap();
466
    let home = tmp.path().join("home");
467
    std::fs::create_dir_all(&home).unwrap();
468
    let r = tmp.path().join("repo");
469
    assert_eq!(oxy(tmp.path(), &home, &["init", r.to_str().unwrap()]).0, 0);
470
    write(&r, "a.txt", "a\n");
471
    assert_eq!(oxy(&r, &home, &["commit", "-m", "A"]).0, 0);
472
473
    let repo = oxy_core::repo::Repo::open(&r).unwrap();
474
    let heads = repo.bookmark_heads().unwrap();
475
    let state = oxy_core::hash::hash_object(ObjectType::State, &StateObject::new(heads).encode());
476
    let receipt = Receipt {
477
        job_name: "test".into(),
478
        pipeline_hash: ObjectRef([1; 32]),
479
        scope_tree_hash: ObjectRef([2; 32]),
480
        inputs: vec![],
481
        environment: ObjectRef([3; 32]),
482
        outputs: vec![],
483
        exit_code: 0,
484
        duration_ms: 2500,
485
    };
486
    let sk = SecretKey::generate();
487
    let runner = sk.identity("earth-1", "runner@earth", 1);
488
    let sr = SignedReceipt::sign(receipt, repo.id().unwrap(), state, "demo#7", &runner, &sk);
489
    let file = tmp.path().join("r.receipt");
490
    std::fs::write(&file, sr.encode()).unwrap();
491
    let f = file.to_str().unwrap();
492
493
    let v = json(&r, &home, &["receipt", "verify", f, "--json"]);
494
    assert_eq!(
495
        (v["valid"].as_bool(), v["job"].as_str(), v["run"].as_str()),
496
        (Some(true), Some("test"), Some("demo#7"))
497
    );
498
    assert!(v["attest"].is_null());
499
500
    assert!(json(&r, &home, &["receipt", "list", "--json"])
501
        .as_array()
502
        .unwrap()
503
        .is_empty());
504
    assert_eq!(oxy(&r, &home, &["receipt", "import", f]).0, 0);
505
    let list = json(&r, &home, &["receipt", "list", "--json"]);
506
    let list = list.as_array().unwrap();
507
    assert_eq!(list.len(), 1);
508
    assert_eq!(list[0]["runner_name"], "earth-1");
509
    assert_eq!(list[0]["state"], state.to_hex());
510
    let attest = list[0]["attest"].as_str().unwrap().to_string();
511
    let shown = json(&r, &home, &["receipt", "show", &attest[..10], "--json"]);
512
    assert_eq!(shown["duration_ms"], 2500);
513
514
    let out = tmp.path().join("out.receipt");
515
    assert_eq!(
516
        oxy(
517
            &r,
518
            &home,
519
            &["receipt", "export", &attest[..10], out.to_str().unwrap()]
520
        )
521
        .0,
522
        0
523
    );
524
    assert_eq!(std::fs::read(&out).unwrap(), sr.encode());
525
a39754d0 Andy McCall ↶ 526
    // SLSA provenance is signed with the exporter's key: none yet, so it is
527
    // refused and says what to do.
528
    let prov = tmp.path().join("prov.json");
529
    let p = prov.to_str().unwrap();
530
    let slsa = ["receipt", "export", &attest[..10], p, "--format", "slsa"];
531
    let (code, _, err) = oxy(&r, &home, &slsa);
532
    assert_ne!(code, 0);
533
    assert!(err.contains("oxy identity create"), "{err}");
534
    let ident = [
535
        "identity",
536
        "create",
537
        "--name",
538
        "Ada",
539
        "--email",
540
        "[email protected]",
541
    ];
542
    assert_eq!(oxy(&r, &home, &ident).0, 0);
543
    assert_eq!(oxy(&r, &home, &slsa).0, 0);
544
    let env: serde_json::Value = serde_json::from_slice(&std::fs::read(&prov).unwrap()).unwrap();
545
    assert_eq!(env["payloadType"], oxy_core::dsse::IN_TOTO);
546
    let payload = oxy_core::dsse::base64_decode(env["payload"].as_str().unwrap()).unwrap();
547
    let st: serde_json::Value = serde_json::from_slice(&payload).unwrap();
548
    assert_eq!(st["predicateType"], "https://slsa.dev/provenance/v1");
549
    assert_eq!(st["subject"][0]["digest"]["oxygen-state"], state.to_hex());
550
    let run = &st["predicate"]["runDetails"];
551
    assert_eq!(run["metadata"]["invocationId"], "demo#7");
552
    let kept = oxy_core::dsse::base64_decode(run["byproducts"][0]["content"].as_str().unwrap());
553
    assert_eq!(
554
        kept.unwrap(),
555
        sr.encode(),
556
        "the runner's receipt rides along"
557
    );
558
    // It verifies with the exporter's key and its PEM holds that key.
559
    let repo = oxy_core::repo::Repo::open(&r)
560
        .unwrap()
561
        .with_home(home.clone());
562
    let key = repo.signing_key().unwrap();
563
    assert_eq!(env["signatures"][0]["keyid"], key.to_hex());
564
    let me = repo.identity(&key).unwrap();
565
    let sig = oxy_core::dsse::base64_decode(env["signatures"][0]["sig"].as_str().unwrap()).unwrap();
566
    assert!(oxy_core::dsse::verify(&me, oxy_core::dsse::IN_TOTO, &payload, &sig).is_ok());
567
    assert!(oxy_core::dsse::verify(&runner, oxy_core::dsse::IN_TOTO, &payload, &sig).is_err());
568
    let pem = tmp.path().join("key.pem");
569
    let pem_args = ["identity", "export", "--pem", pem.to_str().unwrap()];
570
    assert_eq!(oxy(&r, &home, &pem_args).0, 0);
571
    assert_eq!(
572
        std::fs::read_to_string(&pem).unwrap(),
573
        oxy_core::dsse::public_pem(&me)
574
    );
575
fc1a466a Andy McCall ↶ 576
    // A receipt whose result was changed after signing does not verify.
577
    let mut forged = sr.clone();
578
    forged.receipt.exit_code = 3;
579
    std::fs::write(&file, forged.encode()).unwrap();
580
    let (code, out, _) = oxy(&r, &home, &["receipt", "verify", f]);
581
    assert_eq!(code, 1);
582
    assert!(String::from_utf8_lossy(&out).contains("different receipt"));
583
    let (code, _, err) = oxy(&r, &home, &["receipt", "import", f]);
584
    assert_ne!(code, 0);
585
    assert!(err.contains("does not verify"), "{err}");
586
}
4fe7d604 Andy McCall ↶ 587
588
/// Metalgear, 2026-09-29 (oxygen#37): a bookmark created at one of three
589
/// independent heads held only that change and what it depends on, and
590
/// switching to it silently wrote a much older tree.
591
#[test]
592
fn a_bookmark_at_one_head_of_several_is_refused_unless_asked_for() {
593
    let tmp = tempfile::tempdir().unwrap();
594
    let home = tmp.path().join("home");
595
    std::fs::create_dir_all(&home).unwrap();
596
    let r = tmp.path().join("repo");
597
    assert_eq!(oxy(tmp.path(), &home, &["init", r.to_str().unwrap()]).0, 0);
598
    for f in ["a", "b", "c"] {
599
        write(&r, &format!("{f}.txt"), &format!("{f}\n"));
600
        assert_eq!(oxy(&r, &home, &["commit", "-m", f]).0, 0);
601
    }
602
    let bms = json(&r, &home, &["bookmark", "list", "--json"]);
603
    assert_eq!(
604
        bms[0]["heads"].as_array().unwrap().len(),
605
        3,
606
        "independent: {bms}"
607
    );
608
    let log = json(&r, &home, &["log", "--json"]);
609
    let hash = |m: &str| {
610
        let c = log["changes"]
611
            .as_array()
612
            .unwrap()
613
            .iter()
614
            .find(|c| c["message"] == m)
615
            .unwrap();
616
        format!("#{}", &c["hash"].as_str().unwrap()[..12])
617
    };
618
    let b = hash("b");
619
620
    let (code, _, err) = oxy(&r, &home, &["bookmark", "create", "x", &b]);
621
    assert_ne!(code, 0);
622
    assert!(
623
        err.contains("would lack 1 change") && err.contains("--upto") && err.contains("--only"),
624
        "{err}"
625
    );
626
627
    assert_eq!(
628
        oxy(&r, &home, &["bookmark", "create", "upto", &b, "--upto"]).0,
629
        0
630
    );
631
    assert_eq!(
632
        oxy(&r, &home, &["bookmark", "create", "only", &b, "--only"]).0,
633
        0
634
    );
635
    let bms = json(&r, &home, &["bookmark", "list", "--json"]);
636
    let heads = |n: &str| {
637
        bms.as_array()
638
            .unwrap()
639
            .iter()
640
            .find(|x| x["name"] == n)
641
            .unwrap()["heads"]
642
            .as_array()
643
            .unwrap()
644
            .len()
645
    };
646
    assert_eq!(heads("upto"), 2, "a and b: {bms}");
647
    assert_eq!(heads("only"), 1);
648
649
    // Switching to the smaller state says what it leaves out.
650
    let (code, out, err) = oxy(&r, &home, &["bookmark", "switch", "only"]);
651
    assert_eq!(code, 0, "{err}");
652
    let out = String::from_utf8_lossy(&out);
653
    assert!(out.contains("only lacks 2 changes that main has"), "{out}");
654
    assert!(!r.join("a.txt").exists() && r.join("b.txt").exists());
06d16dc2 Andy McCall ↶ 655
656
    // Moving a bookmark asks the same (metalgear, oxygen#42): main at b
657
    // alone would lose a, which it holds and was recorded before b.
658
    let (code, _, err) = oxy(&r, &home, &["bookmark", "set", "main", &b]);
659
    assert_ne!(code, 0);
660
    assert!(
661
        err.contains("would lose 1 change") && err.contains("--upto"),
662
        "{err}"
663
    );
664
    assert_eq!(
665
        oxy(&r, &home, &["bookmark", "set", "main", &b, "--upto"]).0,
666
        0
667
    );
668
    let bms = json(&r, &home, &["bookmark", "list", "--json"]);
669
    let main = bms
670
        .as_array()
671
        .unwrap()
672
        .iter()
673
        .find(|x| x["name"] == "main")
674
        .unwrap();
675
    assert_eq!(main["heads"].as_array().unwrap().len(), 2, "a and b: {bms}");
4fe7d604 Andy McCall ↶ 676
}
7d9dab13 Andy McCall ↶ 677
14edbaaf Andy McCall ↶ 678
/// oxygen#29: a pull on a feature bookmark said only "Already up to date"
679
/// while main was behind. Since oxygen#48 it updates main too, and says so.
7d9dab13 Andy McCall ↶ 680
#[test]
14edbaaf Andy McCall ↶ 681
fn pull_names_its_bookmark_and_the_others_it_moved() {
7d9dab13 Andy McCall ↶ 682
    let tmp = tempfile::tempdir().unwrap();
683
    let home = tmp.path().join("home");
684
    std::fs::create_dir_all(&home).unwrap();
685
    let origin = tmp.path().join("origin");
686
    assert_eq!(
687
        oxy(tmp.path(), &home, &["init", origin.to_str().unwrap()]).0,
688
        0
689
    );
690
    let (a, b) = (tmp.path().join("a"), tmp.path().join("b"));
691
    for d in [&a, &b] {
692
        assert_eq!(
693
            oxy(
694
                tmp.path(),
695
                &home,
696
                &["clone", origin.to_str().unwrap(), d.to_str().unwrap()]
697
            )
698
            .0,
699
            0
700
        );
701
    }
702
    write(&a, "one.txt", "one\n");
703
    assert_eq!(oxy(&a, &home, &["commit", "-m", "one"]).0, 0);
704
    assert_eq!(oxy(&a, &home, &["push"]).0, 0);
705
    assert_eq!(oxy(&b, &home, &["pull"]).0, 0);
706
    assert_eq!(oxy(&b, &home, &["bookmark", "create", "feat"]).0, 0);
707
    assert_eq!(oxy(&b, &home, &["bookmark", "switch", "feat"]).0, 0);
708
    assert_eq!(oxy(&b, &home, &["push", "-b", "feat"]).0, 0);
709
    write(&a, "two.txt", "two\n");
710
    assert_eq!(oxy(&a, &home, &["commit", "-m", "two"]).0, 0);
711
    assert_eq!(oxy(&a, &home, &["push"]).0, 0);
712
713
    let (code, out, err) = oxy(&b, &home, &["pull"]);
714
    assert_eq!(code, 0, "{err}");
715
    let out = String::from_utf8_lossy(&out);
716
    assert!(out.contains("feat is up to date with origin"), "{out}");
14edbaaf Andy McCall ↶ 717
    assert!(out.contains("Also updated main"), "{out}");
718
    assert!(!out.contains("behind"), "{out}");
7d9dab13 Andy McCall ↶ 719
}
da868d5d Andy McCall ↶ 720
721
/// oxygen#35: a clean status is answered from the manifest, loading no
722
/// history; any change, a mode change included, falls back to a snapshot.
723
#[test]
724
fn a_clean_status_needs_no_history_and_misses_no_change() {
725
    use std::os::unix::fs::PermissionsExt;
726
    let tmp = tempfile::tempdir().unwrap();
727
    let home = tmp.path().join("home");
728
    std::fs::create_dir_all(&home).unwrap();
729
    let r = tmp.path().join("repo");
730
    assert_eq!(oxy(tmp.path(), &home, &["init", r.to_str().unwrap()]).0, 0);
731
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
732
    for f in ["a.txt", "b.txt"] {
733
        write(&r, f, &format!("{f}\n"));
734
        std::fs::File::options()
735
            .write(true)
736
            .open(r.join(f))
737
            .unwrap()
738
            .set_modified(old)
739
            .unwrap();
740
    }
741
    assert_eq!(oxy(&r, &home, &["commit", "-m", "two"]).0, 0);
742
    let status = |r: &Path| {
743
        let out = Command::new(env!("CARGO_BIN_EXE_oxy"))
744
            .args(["--plain", "status"])
745
            .current_dir(r)
746
            .env("OXY_HOME", &home)
747
            .env("NO_COLOR", "1")
748
            .env("OXY_TIMINGS", "1")
749
            .output()
750
            .unwrap();
751
        (
752
            String::from_utf8_lossy(&out.stdout).to_string(),
753
            String::from_utf8_lossy(&out.stderr).to_string(),
754
        )
755
    };
756
    let (out, err) = status(&r);
757
    assert!(out.contains("working copy clean"), "{out}");
758
    assert!(!err.contains("snapshot"), "no snapshot was needed: {err}");
759
760
    // A mode change alters neither size nor time.
761
    std::fs::set_permissions(r.join("a.txt"), std::fs::Permissions::from_mode(0o755)).unwrap();
762
    let (out, err) = status(&r);
763
    assert!(out.contains("a.txt"), "{out}");
764
    assert!(err.contains("snapshot"), "{err}");
765
    std::fs::set_permissions(r.join("a.txt"), std::fs::Permissions::from_mode(0o644)).unwrap();
766
767
    // A new file.
768
    write(&r, "c.txt", "c\n");
769
    let (out, _) = status(&r);
770
    assert!(out.contains("c.txt"), "{out}");
771
}
d4dbab97 Andy McCall ↶ 772
773
#[test]
774
fn a_nested_git_repository_is_named_not_silently_skipped() {
775
    let tmp = tempfile::tempdir().unwrap();
776
    let home = tmp.path().join("home");
777
    std::fs::create_dir_all(&home).unwrap();
778
    let r = tmp.path().join("repo");
779
    std::fs::create_dir_all(&r).unwrap();
780
    assert_eq!(oxy(&r, &home, &["init", "."]).0, 0);
781
    write(&r, "a.txt", "a\n");
782
    write(&r, "rust-core/src/lib.rs", "pub fn f() {}\n");
783
    write(&r, "rust-core/.git/HEAD", "ref: refs/heads/main\n");
784
    let st = json(&r, &home, &["status", "--json"]);
785
    assert_eq!(st["untracked_nested"], serde_json::json!(["rust-core"]));
786
    let (code, out, err) = oxy(&r, &home, &["commit", "-m", "first"]);
787
    assert_eq!(code, 0, "{err}");
788
    let out = String::from_utf8_lossy(&out);
789
    assert!(
790
        out.contains("rust-core/") && out.contains("nested Git repository"),
791
        "{out}"
792
    );
793
    // The clean status says so too.
794
    let (_, out, _) = oxy(&r, &home, &["status"]);
795
    let out = String::from_utf8_lossy(&out);
796
    assert!(
797
        out.contains("working copy clean") && out.contains("rust-core/"),
798
        "{out}"
799
    );
800
}
2bf22305 Andy McCall ↶ 801
802
/// oxygen#50: the log is a graph. Two changes that build on the same one
803
/// take two lanes that join above it; each change shows its ID, author,
804
/// time and hash on one line and its subject on the next.
805
#[test]
806
fn the_log_draws_lanes_that_join() {
807
    let tmp = tempfile::tempdir().unwrap();
808
    let home = tmp.path().join("home");
809
    std::fs::create_dir_all(&home).unwrap();
810
    let repo = tmp.path().join("r");
811
    assert_eq!(oxy(tmp.path(), &home, &["init", repo.to_str().unwrap()]).0, 0);
812
    write(&repo, "a.txt", "a\n");
813
    write(&repo, "b.txt", "b\n");
814
    assert_eq!(oxy(&repo, &home, &["commit", "-m", "both files"]).0, 0);
815
    write(&repo, "a.txt", "a\na2\n");
816
    assert_eq!(oxy(&repo, &home, &["commit", "-m", "edit a"]).0, 0);
817
    write(&repo, "b.txt", "b\nb2\n");
818
    assert_eq!(oxy(&repo, &home, &["commit", "-m", "edit b"]).0, 0);
819
820
    let (code, out, err) = oxy(&repo, &home, &["log"]);
821
    assert_eq!(code, 0, "{err}");
822
    let out = String::from_utf8_lossy(&out);
823
    let lines: Vec<&str> = out.lines().collect();
824
    // The working copy, then "edit b", "edit a" beside it, then their base.
825
    assert!(lines[0].starts_with('@'), "{out}");
826
    assert!(lines.iter().any(|l| l.starts_with("|-'") && l.contains("edit a")), "{out}");
827
    assert!(lines.iter().any(|l| l.starts_with("| *") || l.starts_with("| o")), "{out}");
828
    let base = lines.iter().position(|l| l.contains("both files")).unwrap();
829
    assert!(lines[base - 1].contains('#'), "the header line carries the hash: {out}");
830
}