brygge 0.8.0

Carry version-control history from one system to another: decode Git, Mercurial, Subversion and CVS into a portable, verifiable IR artifact, with every inference marked and every loss recorded, and encode it into a target.
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
//! End-to-end subprocess proof of `brygge encode` (RFC 017 D-3, review request 059): the properties only
//! observable at the process boundary — real spawning, real `PATH` search, real exit codes, real signal
//! delivery — that a unit test inside `src/` cannot see.
//!
//! One sibling binary, built in the same `cargo build`/`cargo test --workspace` as `brygge` itself and
//! found alongside it in the target directory (never through `CARGO_BIN_EXE_*`, which Cargo sets only for
//! binaries of *this* package): `brygge-encode-test-plugin` (`tools/encode-test-plugin`), a controllable
//! fake plugin for the lookup, verify-first, pass-through and argument tests. (The retired
//! `examples/encode-git`'s own real-plugin round-trip test moved to the built-in `encode git`'s own
//! level-2 proof, `tests/encode_git_fast_import.rs`, since RFC 019 made `git` a reserved, built-in
//! target rather than a plugin.)
//!
//! This is a workspace-built binary, not a system tool whose absence is legitimate (like `git`, which
//! these tests do skip for): if it is missing, the test that needs it **fails**, naming the fix
//! (`cargo test --workspace`), rather than silently reporting `ok` for a test that never ran (review 093
//! R-1/R-2). A bare `cargo test -p brygge`, without `--workspace`, does not build it and so fails these
//! tests on purpose; CI, the MSRV job and the AUR `check()` all run `--workspace`.

#![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;
#[cfg(unix)]
const FAILURE: i32 = 1;

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

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

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

/// Every workspace binary built in the same `cargo build`/`cargo test --workspace` session lands beside
/// `brygge`'s own binary — that directory, not `current_exe()`'s, which cargo has moved more than once
/// (review 115: cargo 1.100 dropped `target/<profile>/deps/`, writing a test executable's directory
/// under `target/<profile>/build/<pkg>/<hash>/out/` instead). `CARGO_BIN_EXE_brygge` is the one path
/// cargo guarantees, so its parent is always right regardless of where the test binary itself landed.
fn workspace_bin_dir() -> PathBuf {
    Path::new(bin())
        .parent()
        .expect("CARGO_BIN_EXE_brygge has a parent")
        .to_path_buf()
}

fn exe_name(name: &str) -> String {
    if cfg!(windows) {
        format!("{name}.exe")
    } else {
        name.to_string()
    }
}

/// The path to a sibling workspace binary — **fails the test** (never skips) if it was not built: unlike
/// a system tool such as `git`, this is a binary brygge's own build is supposed to produce, and Cargo
/// builds a package's binaries for `cargo test --workspace` only when that package has an integration
/// test of its own (review 093 R-1) — both `tools/encode-test-plugin` and `examples/encode-git` do, for
/// exactly this reason.
fn sibling_bin(name: &str) -> PathBuf {
    let path = workspace_bin_dir().join(exe_name(name));
    assert!(
        path.is_file(),
        "{name} was not built: build the workspace: `cargo test --workspace`"
    );
    path
}

fn test_plugin_bin() -> PathBuf {
    sibling_bin("brygge-encode-test-plugin")
}

struct TempDir(PathBuf);

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

fn temp_dir(label: &str) -> TempDir {
    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-encode-itest-{label}-{}-{nanos}-{n}",
        std::process::id()
    ));
    std::fs::create_dir_all(&dir).unwrap();
    TempDir(dir)
}

/// Copies `src` into `dir` under the plugin name for `target` (`brygge-encode-<target>[.exe]`), with an
/// execute bit on Unix. Returns the copy's path.
fn install_plugin(dir: &Path, target: &str, src: &Path) -> PathBuf {
    let dest = dir.join(exe_name(&format!("brygge-encode-{target}")));
    std::fs::copy(src, &dest).expect("copy plugin binary");
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o755)).unwrap();
    }
    dest
}

fn write_non_executable_plugin(dir: &Path, target: &str) -> PathBuf {
    let dest = dir.join(exe_name(&format!("brygge-encode-{target}")));
    std::fs::write(&dest, b"not executable\n").unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o644)).unwrap();
    }
    dest
}

/// A valid, empty-but-decodable IR artifact: any path the `verify` checks on, when the test does not care
/// about its contents, built with `brygge decode` on a one-commit repository. Skips (returning `None`) if
/// `git` is not on `PATH`.
fn make_artifact(dir: &Path) -> Option<PathBuf> {
    if !git_available() {
        return None;
    }
    let repo = dir.join("repo");
    std::fs::create_dir_all(&repo).unwrap();
    let git = |args: &[&str]| {
        let out = Command::new("git")
            .current_dir(&repo)
            .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");
    };
    git(&["init", "-q", "--initial-branch=main"]);
    std::fs::write(repo.join("a.txt"), "one\n").unwrap();
    git(&["add", "-A"]);
    git(&["-c", "commit.gpgsign=false", "commit", "-q", "-m", "c1"]);
    let artifact = dir.join("out.ir");
    let out = Command::new(bin())
        .args(["decode", "git"])
        .arg(&repo)
        .arg("--out")
        .arg(&artifact)
        .output()
        .expect("run brygge decode");
    assert!(out.status.success(), "decode failed: {out:?}");
    Some(artifact)
}

fn corrupt(artifact: &Path) {
    let mut bytes = std::fs::read(artifact).unwrap();
    let last = bytes.len() - 1;
    bytes[last] ^= 0xFF;
    std::fs::write(artifact, bytes).unwrap();
}

// ---- lookup (proof item 2) --------------------------------------------------------------------------

#[test]
fn an_invalid_target_is_a_usage_error_before_any_search() {
    for bad in ["../x", "A", "x/y", ""] {
        let output = Command::new(bin())
            .args(["encode", bad, "out.ir"])
            .env("PATH", "")
            .output()
            .expect("run brygge encode");
        assert_eq!(output.status.code(), Some(USAGE), "target {bad:?}");
    }
    // 65 bytes: over the limit.
    let too_long = "a".repeat(65);
    let output = Command::new(bin())
        .args(["encode", &too_long, "out.ir"])
        .env("PATH", "")
        .output()
        .expect("run brygge encode");
    assert_eq!(output.status.code(), Some(USAGE));
}

#[test]
fn not_found_names_the_target_and_points_at_list() {
    let output = Command::new(bin())
        .args(["encode", "nonexistent-target", "out.ir"])
        .env("PATH", "")
        .output()
        .expect("run brygge encode");
    assert_eq!(output.status.code(), Some(USAGE));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("no encoder for 'nonexistent-target'"),
        "{stderr}"
    );
    assert!(
        stderr.contains("brygge-encode-nonexistent-target"),
        "{stderr}"
    );
    assert!(stderr.contains("brygge encode --list"), "{stderr}");
}

#[test]
fn an_empty_and_a_relative_path_entry_are_skipped() {
    let plugin = test_plugin_bin();
    let scratch = temp_dir("relpath");
    // A decoy at the relative path, resolved against the child's current directory — must never be
    // found, since a relative PATH entry is always skipped.
    let decoy_dir = scratch.0.join("relative-dir");
    std::fs::create_dir_all(&decoy_dir).unwrap();
    install_plugin(&decoy_dir, "foo", &plugin);
    // The real plugin, at an absolute path later in PATH.
    let real_dir = scratch.0.join("real");
    std::fs::create_dir_all(&real_dir).unwrap();
    let real_plugin = install_plugin(&real_dir, "foo", &plugin);

    let sep = if cfg!(windows) { ';' } else { ':' };
    let path_value = format!("{sep}relative-dir{sep}{sep}{}", real_dir.display());
    let Some(artifact) = make_artifact(&scratch.0) else {
        eprintln!("skipping: git not on PATH");
        return;
    };
    let output = Command::new(bin())
        .args(["encode", "foo"])
        .arg(&artifact)
        .env("PATH", &path_value)
        .current_dir(&scratch.0)
        .output()
        .expect("run brygge encode");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(output.status.success(), "{stderr}");
    assert!(
        stderr.contains(&real_plugin.display().to_string()),
        "the banner must name the real (absolute-PATH) plugin: {stderr}"
    );
}

#[test]
fn a_non_executable_file_is_skipped_and_the_search_continues() {
    if cfg!(windows) {
        eprintln!("skipping: this test's premise (a non-executable regular file) is Unix-only");
        return;
    }
    let plugin = test_plugin_bin();
    let scratch = temp_dir("nonexec");
    let a = scratch.0.join("a");
    std::fs::create_dir_all(&a).unwrap();
    write_non_executable_plugin(&a, "foo");
    let b = scratch.0.join("b");
    std::fs::create_dir_all(&b).unwrap();
    let real_plugin = install_plugin(&b, "foo", &plugin);

    let Some(artifact) = make_artifact(&scratch.0) else {
        eprintln!("skipping: git not on PATH");
        return;
    };
    let sep = if cfg!(windows) { ';' } else { ':' };
    let path_value = format!("{}{sep}{}", a.display(), b.display());
    let output = Command::new(bin())
        .args(["encode", "foo"])
        .arg(&artifact)
        .env("PATH", &path_value)
        .output()
        .expect("run brygge encode");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(output.status.success(), "{stderr}");
    assert!(
        stderr.contains(&real_plugin.display().to_string()),
        "{stderr}"
    );
}

#[test]
fn a_non_executable_file_alone_is_not_found() {
    if cfg!(windows) {
        eprintln!("skipping: this test's premise (a non-executable regular file) is Unix-only");
        return;
    }
    let scratch = temp_dir("nonexec-alone");
    write_non_executable_plugin(&scratch.0, "foo");
    let output = Command::new(bin())
        .args(["encode", "foo", "out.ir"])
        .env("PATH", &scratch.0)
        .output()
        .expect("run brygge encode");
    assert_eq!(output.status.code(), Some(USAGE));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("no encoder for 'foo'"), "{stderr}");
}

#[test]
fn two_directories_with_the_plugin_the_first_runs_and_list_shows_the_second_shadowed() {
    let plugin = test_plugin_bin();
    let scratch = temp_dir("shadow");
    let a = scratch.0.join("a");
    std::fs::create_dir_all(&a).unwrap();
    let b = scratch.0.join("b");
    std::fs::create_dir_all(&b).unwrap();
    let a_plugin = install_plugin(&a, "foo", &plugin);
    let b_plugin = install_plugin(&b, "foo", &plugin);
    let sep = if cfg!(windows) { ';' } else { ':' };
    let path_value = format!("{}{sep}{}", a.display(), b.display());

    let Some(artifact) = make_artifact(&scratch.0) else {
        eprintln!("skipping: git not on PATH");
        return;
    };
    let output = Command::new(bin())
        .args(["encode", "foo"])
        .arg(&artifact)
        .env("PATH", &path_value)
        .output()
        .expect("run brygge encode");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(output.status.success(), "{stderr}");
    assert!(
        stderr.contains(&a_plugin.display().to_string()),
        "the first PATH directory's plugin must be the one named/run: {stderr}"
    );

    let list_output = Command::new(bin())
        .args(["encode", "--list", "--format", "machine"])
        .env("PATH", &path_value)
        .output()
        .expect("run brygge encode --list");
    assert!(list_output.status.success());
    let stdout = String::from_utf8_lossy(&list_output.stdout);
    // RFC 019 bumped this to 2 (git's always-shadowed-by-the-built-in meaning).
    assert!(stdout.contains("encode_list_version=2"), "{stdout}");
    let path_line = stdout
        .lines()
        .find(|l| l.starts_with("encoder.0.path="))
        .unwrap_or_else(|| panic!("no encoder.0.path line: {stdout}"));
    let decoded = percent_decode(path_line.trim_start_matches("encoder.0.path="));
    assert_eq!(
        decoded,
        a_plugin.display().to_string(),
        "encoder.0 must be the first (unshadowed) PATH directory's plugin: {stdout}"
    );
    assert!(stdout.contains("encoder.0.shadowed=false"), "{stdout}");
    assert!(stdout.contains("encoder.1.shadowed=true"), "{stdout}");
    let _ = b_plugin;
}

/// Percent-decodes a machine-format value (`display::machine_value`'s inverse): every `%XX` becomes that
/// byte, everything else passes through. Assumes (as this test's values do) the result is valid UTF-8.
fn percent_decode(s: &str) -> String {
    let bytes = s.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' && i + 2 < bytes.len() {
            if let Ok(byte) = u8::from_str_radix(&s[i + 1..i + 3], 16) {
                out.push(byte);
                i += 3;
                continue;
            }
        }
        out.push(bytes[i]);
        i += 1;
    }
    String::from_utf8(out).expect("valid UTF-8")
}

// ---- verify first (proof item 3) --------------------------------------------------------------------

#[test]
fn a_corrupted_artifact_is_refused_and_the_plugin_never_runs() {
    let plugin = test_plugin_bin();
    let scratch = temp_dir("verify-first");
    install_plugin(&scratch.0, "foo", &plugin);
    let Some(artifact) = make_artifact(&scratch.0) else {
        eprintln!("skipping: git not on PATH");
        return;
    };
    corrupt(&artifact);
    let marker = scratch.0.join("marker");
    let output = Command::new(bin())
        .args(["encode", "foo"])
        .arg(&artifact)
        .args(["--", "--marker"])
        .arg(&marker)
        .env("PATH", &scratch.0)
        .output()
        .expect("run brygge encode");
    assert!(!output.status.success());
    assert_ne!(output.status.code(), Some(0));
    assert!(!marker.exists(), "the plugin must never have started");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("verify_version") || stderr.contains("verify —"),
        "verify's own report must be printed: {stderr}"
    );
    assert!(output.stdout.is_empty(), "stdout must stay empty");
}

// ---- pass-through (proof item 4) and arguments (proof item 5) ----------------------------------------

#[test]
fn exit_codes_pass_through_unchanged() {
    let plugin = test_plugin_bin();
    let scratch = temp_dir("exit-codes");
    install_plugin(&scratch.0, "foo", &plugin);
    let Some(artifact) = make_artifact(&scratch.0) else {
        eprintln!("skipping: git not on PATH");
        return;
    };
    for code in [0, 3, 77] {
        let output = Command::new(bin())
            .args(["encode", "foo"])
            .arg(&artifact)
            .args(["--", "--then-exit", &code.to_string()])
            .env("PATH", &scratch.0)
            .output()
            .expect("run brygge encode");
        assert_eq!(output.status.code(), Some(code), "code {code}");
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains(&format!("exited with {code}")), "{stderr}");
    }
}

#[cfg(unix)]
#[test]
fn a_self_killed_plugin_exits_1_with_the_signal_named() {
    let plugin = test_plugin_bin();
    let scratch = temp_dir("signal");
    install_plugin(&scratch.0, "foo", &plugin);
    let Some(artifact) = make_artifact(&scratch.0) else {
        eprintln!("skipping: git not on PATH");
        return;
    };
    let output = Command::new(bin())
        .args(["encode", "foo"])
        .arg(&artifact)
        .args(["--", "--then-abort"])
        .env("PATH", &scratch.0)
        .output()
        .expect("run brygge encode");
    assert_eq!(output.status.code(), Some(FAILURE));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("SIGABRT"), "{stderr}");
    assert!(stderr.contains('6'), "{stderr}");
}

#[test]
fn arguments_reach_the_plugin_verbatim_with_no_shell() {
    let plugin = test_plugin_bin();
    let scratch = temp_dir("argv");
    install_plugin(&scratch.0, "foo", &plugin);
    let Some(artifact) = make_artifact(&scratch.0) else {
        eprintln!("skipping: git not on PATH");
        return;
    };
    let tricky = [
        "has space",
        "has\"quote",
        "-leading-dash",
        "non-ascii-é-日本語",
        "$(echo shell-would-expand-this)",
        "a;b|c",
    ];
    let mut cmd = Command::new(bin());
    cmd.args(["encode", "foo"]).arg(&artifact).arg("--");
    for a in &tricky {
        cmd.arg(a);
    }
    cmd.env("PATH", &scratch.0);
    let output = cmd.output().expect("run brygge encode");
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    for a in &tricky {
        assert!(stdout.contains(&format!("argv: {a}")), "{stdout}");
    }
}