brygge 0.4.0

Carry version-control history out of Git, Mercurial, Subversion and CVS into an intermediate representation (IR), with every inference marked and every loss recorded: decode, inspect and verify.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
//! End-to-end subprocess tests against the real compiled binary (handoff `cli-and-verify-handoff-v2.md`
//! §5.2): properties only observable at the process boundary — real stderr, real exit codes — that a
//! unit test inside `src/` cannot see (`CARGO_BIN_EXE_brygge` is only set for `tests/*.rs`). Skips
//! without `git` on `PATH`.

#![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]

use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicU64, Ordering};

const USAGE: i32 = 2;
const FLOOR_REFUSAL: i32 = 20;

static COUNTER: AtomicU64 = AtomicU64::new(0);

fn git_available() -> bool {
    Command::new("git")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

struct TempRepo {
    dir: PathBuf,
}

impl Drop for TempRepo {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.dir);
    }
}

impl TempRepo {
    fn new() -> Self {
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let n = COUNTER.fetch_add(1, Ordering::Relaxed);
        let dir = std::env::temp_dir().join(format!(
            "brygge-cli-itest-{}-{nanos}-{n}",
            std::process::id()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let r = Self { dir };
        r.git(&["init", "-q", "--initial-branch=main"]);
        r
    }

    fn path(&self) -> &Path {
        &self.dir
    }

    fn git(&self, args: &[&str]) -> String {
        let out = Command::new("git")
            .current_dir(&self.dir)
            .args(args)
            .env("GIT_AUTHOR_NAME", "A U Thor")
            .env("GIT_AUTHOR_EMAIL", "author@example.com")
            .env("GIT_AUTHOR_DATE", "2005-04-07T22:13:13 +0000")
            .env("GIT_COMMITTER_NAME", "C O Mitter")
            .env("GIT_COMMITTER_EMAIL", "committer@example.com")
            .env("GIT_COMMITTER_DATE", "2005-04-07T22:13:13 +0000")
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .env("GIT_CONFIG_SYSTEM", "/dev/null")
            .output()
            .expect("run git");
        assert!(out.status.success(), "git {args:?} failed");
        String::from_utf8_lossy(&out.stdout).trim().to_string()
    }

    fn commit(&self, file: &str, contents: &str, msg: &str) {
        std::fs::write(self.dir.join(file), contents).unwrap();
        self.git(&["add", "-A"]);
        self.git(&["-c", "commit.gpgsign=false", "commit", "-q", "-m", msg]);
    }
}

fn bin() -> &'static str {
    env!("CARGO_BIN_EXE_brygge")
}

#[test]
fn faithfulness_statement_reaches_stderr_even_when_decode_then_fails() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = TempRepo::new();
    repo.commit("a.txt", "one\n", "c1");
    // A submodule triggers a floor refusal (decode fails) after the statement must already be printed.
    let head = repo.git(&["rev-parse", "HEAD"]);
    repo.git(&[
        "update-index",
        "--add",
        "--cacheinfo",
        &format!("160000,{head},sub"),
    ]);
    repo.git(&[
        "-c",
        "commit.gpgsign=false",
        "commit",
        "-q",
        "-m",
        "add gitlink",
    ]);
    let out = repo.dir.join("out.ir");
    let output = Command::new(bin())
        .args(["decode", "git"])
        .arg(repo.path())
        .arg("--out")
        .arg(&out)
        .output()
        .expect("run brygge decode");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        output.status.code(),
        Some(FLOOR_REFUSAL),
        "stderr: {stderr}"
    );
    assert!(
        stderr.contains(
            "Git: content, history and messages are carried as the source recorded them."
        ),
        "the faithfulness statement must print even though decode then fails: {stderr}"
    );
    assert!(!out.exists(), "no artifact is written on a refusal");
}

#[test]
fn faithfulness_statement_reaches_stderr_on_a_successful_decode_too() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = TempRepo::new();
    repo.commit("a.txt", "one\n", "c1");
    let out = repo.dir.join("out.ir");
    let output = Command::new(bin())
        .args(["decode", "git"])
        .arg(repo.path())
        .arg("--out")
        .arg(&out)
        .output()
        .expect("run brygge decode");
    assert_eq!(output.status.code(), Some(0));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("Git: content, history and messages"));
    assert!(stderr.contains(&format!("wrote {}", out.display())));
}

#[test]
fn a_usage_error_exits_2_and_names_the_problem() {
    let output = Command::new(bin())
        .args(["decode", "git", "/does-not-matter"])
        .output()
        .expect("run brygge decode without --out");
    assert_eq!(output.status.code(), Some(USAGE));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("--out"), "{stderr}");
    assert!(stderr.contains("brygge decode --help"), "{stderr}");
}

#[test]
fn an_inapplicable_option_exits_2_with_the_exact_message() {
    let output = Command::new(bin())
        .args([
            "decode",
            "svn",
            "/does-not-matter",
            "--out",
            "o.ir",
            "--infer-renames",
        ])
        .output()
        .expect("run brygge decode");
    assert_eq!(output.status.code(), Some(USAGE));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("--infer-renames applies to git, not to svn"),
        "{stderr}"
    );
}

#[test]
fn encode_exits_2_with_its_own_message() {
    let output = Command::new(bin())
        .arg("encode")
        .output()
        .expect("run brygge encode");
    assert_eq!(output.status.code(), Some(USAGE));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("'encode' is not available yet"), "{stderr}");
}

#[test]
fn help_lists_only_existing_commands() {
    let output = Command::new(bin())
        .arg("--help")
        .output()
        .expect("run brygge --help");
    assert_eq!(output.status.code(), Some(0));
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("decode"));
    assert!(stdout.contains("inspect"));
    assert!(stdout.contains("verify"));
    assert!(
        !stdout.contains("summary"),
        "the removed verb must not be listed"
    );
    assert!(
        !stdout.contains("encode"),
        "no placeholder for a command that does not exist yet (review 003 R-4, CL-03/CL-06)"
    );
}

#[test]
fn infer_renames_for_hg_exits_2_because_mercurial_records_its_renames() {
    let output = Command::new(bin())
        .args([
            "decode",
            "hg",
            "/does-not-matter",
            "--out",
            "o.ir",
            "--infer-renames",
        ])
        .output()
        .expect("run brygge decode hg --infer-renames");
    assert_eq!(output.status.code(), Some(USAGE));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("--infer-renames applies to git, not to hg"),
        "{stderr}"
    );
    assert!(stderr.contains("brygge decode --help"), "{stderr}");
    // ... and the help says so too.
    let help = Command::new(bin()).arg("--help").output().unwrap();
    let help = String::from_utf8_lossy(&help.stdout);
    assert!(help.contains("--infer-renames (git)"), "{help}");
}

/// Every machine line is `key=value` with a key of dot-separated `[a-z0-9_]` segments.
fn assert_keys_follow_the_rule(stdout: &str, what: &str) {
    for line in stdout.lines() {
        let (key, _) = line
            .split_once('=')
            .unwrap_or_else(|| panic!("{what}: a machine line without `=`: {line:?}"));
        assert!(!key.is_empty(), "{what}: empty key in {line:?}");
        for seg in key.split('.') {
            assert!(
                !seg.is_empty()
                    && seg
                        .bytes()
                        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_'),
                "{what}: key {key:?} breaks `^[a-z0-9_]+(\\.[a-z0-9_]+)*$`"
            );
        }
    }
}

fn percent_decode(s: &str) -> Vec<u8> {
    let b = s.as_bytes();
    let mut out = Vec::new();
    let mut i = 0;
    while i < b.len() {
        if b[i] == b'%' {
            out.push(
                u8::from_str_radix(std::str::from_utf8(&b[i + 1..i + 3]).unwrap(), 16).unwrap(),
            );
            i += 3;
        } else {
            out.push(b[i]);
            i += 1;
        }
    }
    out
}

#[test]
fn a_real_run_prints_only_rule_following_keys_one_atoms_line_and_the_exact_message_bytes() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = TempRepo::new();
    repo.commit("old.txt", "some content that will move\n", "c1");
    // A non-UTF-8 commit message (Latin-1 é). Git converts an invalid-UTF-8 message to UTF-8 unless the
    // repository declares its commit encoding, so declare Latin-1: the bytes are then stored as given.
    std::fs::rename(repo.dir.join("old.txt"), repo.dir.join("new.txt")).unwrap();
    repo.git(&["add", "-A"]);
    let msg_file = repo
        .dir
        .join("..")
        .join(format!("brygge-msg-{}.txt", std::process::id()));
    std::fs::write(&msg_file, b"caf\xe9 100%\n").unwrap();
    repo.git(&[
        "-c",
        "commit.gpgsign=false",
        "-c",
        "i18n.commitEncoding=ISO-8859-1",
        "commit",
        "-q",
        "-F",
        msg_file.to_str().unwrap(),
    ]);
    let _ = std::fs::remove_file(&msg_file);

    let out = repo.dir.join("out.ir");
    let decode = Command::new(bin())
        .args(["decode", "git"])
        .arg(repo.path())
        .arg("--out")
        .arg(&out)
        .args(["--infer-renames", "--format", "machine"])
        .output()
        .unwrap();
    let decode_out = String::from_utf8(decode.stdout).unwrap();
    assert_keys_follow_the_rule(&decode_out, "decode");
    assert!(
        decode_out.lines().any(|l| l == "report_version=3"),
        "{decode_out}"
    );
    assert!(
        decode_out
            .lines()
            .any(|l| l == "skipped_non_critical_fields=0")
    );
    assert!(
        decode_out
            .lines()
            .any(|l| l.starts_with("derived.inferred_rename=")),
        "{decode_out}"
    );

    let inspect = Command::new(bin())
        .args(["inspect"])
        .arg(&out)
        .args(["--atoms", "--format", "machine"])
        .output()
        .unwrap();
    assert_eq!(inspect.status.code(), Some(0));
    let inspect_out = String::from_utf8(inspect.stdout).unwrap();
    assert_keys_follow_the_rule(&inspect_out, "inspect --atoms");
    assert_eq!(
        inspect_out
            .lines()
            .filter(|l| l.starts_with("atoms="))
            .count(),
        1,
        "one key, one line:\n{inspect_out}"
    );
    assert!(inspect_out.lines().any(|l| l == "inspect_version=4"));
    let message = inspect_out
        .lines()
        .filter_map(|l| l.strip_prefix("atom.1.message="))
        .next()
        .unwrap_or_else(|| panic!("no atom.1.message in\n{inspect_out}"));
    assert_eq!(
        percent_decode(message),
        b"caf\xe9 100%\n",
        "the exact bytes"
    );

    let verify = Command::new(bin())
        .args(["verify"])
        .arg(&out)
        .args(["--format", "machine"])
        .output()
        .unwrap();
    assert_eq!(verify.status.code(), Some(0));
    let verify_out = String::from_utf8(verify.stdout).unwrap();
    assert_keys_follow_the_rule(&verify_out, "verify");
    for line in [
        "verify_version=4",
        "verify.skipped_non_critical_fields=0",
        "verify.check.source_invariants=pass",
        "verify.check.loss_boundary=pass",
        "verify.result=pass",
    ] {
        assert!(
            verify_out.lines().any(|l| l == line),
            "{line} in\n{verify_out}"
        );
    }
}

#[test]
fn a_check_that_could_not_run_says_not_checked_in_both_forms_and_its_detail_follows_its_line() {
    // An artifact that fails to decode: `integrity` fails, and every other check cannot run.
    let path = std::env::temp_dir().join(format!("brygge-garbage-{}.ir", std::process::id()));
    std::fs::write(&path, b"this is not an artifact").unwrap();

    let machine = Command::new(bin())
        .args(["verify"])
        .arg(&path)
        .args(["--format", "machine"])
        .output()
        .unwrap();
    assert_eq!(machine.status.code(), Some(50));
    let m = String::from_utf8(machine.stdout).unwrap();
    assert_keys_follow_the_rule(&m, "verify (garbage)");
    let lines: Vec<&str> = m.lines().collect();
    let structure = lines
        .iter()
        .position(|l| *l == "verify.check.structure=not-checked")
        .unwrap_or_else(|| panic!("{m}"));
    assert!(
        lines[structure + 1].starts_with("verify.check.structure.detail="),
        "{m}"
    );
    assert!(
        lines
            .iter()
            .any(|l| l.starts_with("verify.check.integrity.detail="))
    );
    assert!(!m.contains("n/a"), "{m}");

    let human = Command::new(bin())
        .args(["verify"])
        .arg(&path)
        .output()
        .unwrap();
    let h = String::from_utf8(human.stdout).unwrap();
    assert!(h.contains("[not-checked] structure"), "{h}");
    assert!(!h.contains("n/a"), "{h}");
    let _ = std::fs::remove_file(&path);
}

// ---- the CLI must not panic when its reader closes the pipe (handoff `cli-broken-pipe-handoff-v1.md`) ---

use std::collections::BTreeMap;
use std::io::{BufRead, BufReader, Read as _};

/// Spawn `args`, read at most one line of stdout, then drop that handle (closing our end of the pipe)
/// before waiting for the child. Returns the exit code and the full stderr text.
fn run_and_close_stdout_after_one_line(args: &[&str]) -> (Option<i32>, String) {
    let mut child = Command::new(bin())
        .args(args)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .expect("spawn brygge");
    {
        let stdout = child.stdout.take().expect("piped stdout");
        let mut reader = BufReader::new(stdout);
        let mut line = String::new();
        let _ = reader.read_line(&mut line); // best effort; some reports are a single short line
        // `reader` (and the `ChildStdout` it owns) is dropped here, closing our read end before `wait`.
    }
    let status = child.wait().expect("wait for brygge");
    let mut stderr = String::new();
    child
        .stderr
        .take()
        .expect("piped stderr")
        .read_to_string(&mut stderr)
        .expect("read stderr");
    (status.code(), stderr)
}

/// A synthetic artifact with `n` atoms (one file, modified `n` times), so `inspect --atoms` renders a
/// report far bigger than any pipe buffer (RFC 010-scale default is 64 KiB on Linux): the writer is then
/// genuinely still writing, not merely racing a reader that already drained everything, when our one-line
/// read closes the pipe underneath it.
fn big_artifact(n: usize) -> std::path::PathBuf {
    let mut builder = brygge_ir::builder::IrBuilder::new(brygge_ir::ImportProvenance {
        source: brygge_ir::SourceIdentity {
            kind: brygge_ir::SourceKind::Git,
            repo_id: b"r".to_vec(),
            atom_id: b"r".to_vec(),
            signatures: Vec::new(),
            extras: Vec::new(),
        },
        brygge_version: "0.1.0".into(),
        decoder: "brygge-decode-git".into(),
        decoder_version: "0.1.0".into(),
        params: BTreeMap::new(),
    });
    let mut parent = None;
    for i in 0..n {
        let blob = builder.add_blob(format!("content {i}").into_bytes());
        let op = if i == 0 {
            brygge_ir::model::PathOp::Add {
                path: "f".into(),
                blob,
                mode: 0o100_644,
                status: brygge_ir::status::EpistemicStatus::Stated,
            }
        } else {
            brygge_ir::model::PathOp::Modify {
                path: "f".into(),
                blob,
                mode: 0o100_644,
                status: brygge_ir::status::EpistemicStatus::Stated,
            }
        };
        let id = builder
            .add_atom(brygge_ir::builder::AtomDraft {
                parents: parent.into_iter().collect(),
                ops: vec![op],
                copies: Vec::new(),
                metadata: brygge_ir::model::MetadataClaims::default(),
                source: brygge_ir::model::SourceIdentity {
                    kind: brygge_ir::SourceKind::Git,
                    repo_id: b"r".to_vec(),
                    atom_id: format!("c{i}").into_bytes(),
                    signatures: Vec::new(),
                    extras: Vec::new(),
                },
                status: brygge_ir::status::EpistemicStatus::Stated,
            })
            .expect("add_atom");
        parent = Some(id);
    }
    let ir = builder.finish().expect("finish");
    let bytes = brygge_ir::to_bytes(&ir);
    let path = std::env::temp_dir().join(format!("brygge-cli-big-{}.ir", std::process::id()));
    std::fs::write(&path, &bytes).unwrap();
    path
}

#[test]
fn version_through_a_closed_pipe_does_not_panic() {
    let (code, stderr) = run_and_close_stdout_after_one_line(&["--version"]);
    assert_eq!(code, Some(0), "stderr: {stderr}");
    assert!(!stderr.contains("panicked"), "{stderr}");
}

#[test]
fn inspect_of_a_large_report_through_a_closed_pipe_does_not_panic() {
    // Large enough that the single `write_all` of the rendered report cannot complete in one pipe
    // buffer: the writer is still blocked, mid-write, when our read end closes.
    let path = big_artifact(5_000);
    let (code, stderr) =
        run_and_close_stdout_after_one_line(&["inspect", path.to_str().unwrap(), "--atoms"]);
    let _ = std::fs::remove_file(&path);
    assert_eq!(code, Some(0), "stderr: {stderr}");
    assert!(!stderr.contains("panicked"), "{stderr}");
}

#[test]
fn decode_through_a_closed_pipe_still_writes_a_complete_verifying_artifact() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = TempRepo::new();
    repo.commit("a.txt", "one\n", "c1");
    let out = repo.dir.join("out.ir");
    let (code, stderr) = run_and_close_stdout_after_one_line(&[
        "decode",
        "git",
        repo.path().to_str().unwrap(),
        "--out",
        out.to_str().unwrap(),
    ]);
    assert_eq!(code, Some(0), "stderr: {stderr}");
    assert!(!stderr.contains("panicked"), "{stderr}");
    // The artifact itself does not depend on anyone having read the stdout report.
    assert!(out.exists());
    let verify = Command::new(bin())
        .args(["verify"])
        .arg(&out)
        .output()
        .unwrap();
    assert_eq!(verify.status.code(), Some(0));
}

#[cfg(unix)]
#[test]
fn a_stdout_write_error_that_is_not_a_broken_pipe_exits_failure_with_a_message() {
    // /dev/full always answers ENOSPC: a real, non-pipe stdout write error.
    let full = match std::fs::OpenOptions::new().write(true).open("/dev/full") {
        Ok(f) => f,
        Err(_) => {
            eprintln!("skipping: /dev/full is not available");
            return;
        }
    };
    let out = Command::new(bin())
        .args(["--version"])
        .stdout(full)
        .stderr(std::process::Stdio::piped())
        .output()
        .expect("run brygge");
    assert_eq!(
        out.status.code(),
        Some(1),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("cannot write to stdout"), "{stderr}");
    assert!(!stderr.contains("panicked"), "{stderr}");
}