anodizer-core 0.28.1

Core configuration, context, and template engine for the anodizer release tool
Documentation
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
//! PATH-stub harness for faking external command-line tools in tests.
//!
//! Many stages shell out to external tools — `codesign`/`xcrun` (notarize),
//! `syft` (sbom), `makeself`, `rpmbuild` (srpm), `docker`, `upx`, `appimagetool`.
//! Those code paths are the largest uncovered blocks in the tree precisely
//! because a real run needs the tool installed, often on a specific OS. This
//! harness makes them testable on any host by installing executable stub
//! scripts that emit canned stdout/stderr, exit with a chosen code, optionally
//! create output files, and record every invocation's argv for assertions.
//!
//! Two ways to route a stage at a stub:
//!
//! 1. **Configurable command** (e.g. sbom's `cmd:`): point the config value
//!    straight at [`FakeToolDir::tool_path`] — no PATH mutation, no `#[serial]`.
//! 2. **Hard-coded tool name** (e.g. notarize's `codesign`): call
//!    [`FakeToolDir::activate`] to prepend the stub dir to `PATH`. This mutates
//!    the process environment, so such tests **must** be `#[serial]` (the guard
//!    holds [`crate::test_helpers::env::env_mutex`] for its lifetime and
//!    restores the prior `PATH` on drop).
//!
//! ## Example — configurable command (sbom)
//!
//! ```no_run
//! use anodizer_core::test_helpers::fake_tool::FakeToolDir;
//!
//! let tools = FakeToolDir::new();
//! tools
//!     .tool("syft")
//!     .creates("sbom.spdx.json", "{}")
//!     .stdout("generated 1 document\n")
//!     .install();
//! // point the sbom `cmd:` config at tools.tool_path("syft") ...
//! // run the stage ...
//! assert!(tools.was_called("syft"));
//! let argv = tools.calls("syft");
//! assert_eq!(argv[0][0], "scan"); // first arg of the first invocation
//! ```
//!
//! ## Example — hard-coded tool on PATH (notarize), serialised
//!
//! ```no_run
//! use anodizer_core::test_helpers::fake_tool::FakeToolDir;
//!
//! // #[test] #[serial] fn notarize_happy_path() {
//! let tools = FakeToolDir::new();
//! tools.tool("codesign").install();
//! tools.tool("xcrun").stdout("{\"status\":\"Accepted\"}\n").install();
//! let _path = tools.activate(); // prepend to PATH until `_path` drops
//! // run the notarize stage ...
//! // }
//! ```

use std::path::{Path, PathBuf};

use tempfile::TempDir;

use crate::test_helpers::env::env_mutex;

/// Argument separator written by stub scripts between successive argv entries.
const ARG_SEP: char = '\u{1f}';
/// Record separator written by stub scripts after each invocation's argv.
const REC_SEP: char = '\u{1e}';

/// A temporary directory of installed fake-tool stubs.
///
/// Lives for the duration of a test; the backing temp dir (and every stub in
/// it) is deleted when this value drops. Build stubs with [`tool`](Self::tool),
/// route stages at them via [`tool_path`](Self::tool_path) or
/// [`activate`](Self::activate), then assert with [`was_called`](Self::was_called)
/// / [`calls`](Self::calls).
pub struct FakeToolDir {
    dir: TempDir,
}

impl FakeToolDir {
    /// Create a fresh, empty stub directory backed by a temp dir.
    ///
    /// # Panics
    /// Panics if the temp directory cannot be created.
    pub fn new() -> Self {
        let dir = TempDir::new().expect("fake_tool: create temp dir");
        Self { dir }
    }

    /// The directory holding the installed stubs (what [`activate`](Self::activate)
    /// prepends to `PATH`).
    pub fn bin_dir(&self) -> &Path {
        self.dir.path()
    }

    /// Absolute path to a named stub, suitable for a configurable `cmd:` field.
    /// The stub need not exist yet; pair with [`tool`](Self::tool)`.install()`.
    pub fn tool_path(&self, name: &str) -> PathBuf {
        self.dir.path().join(stub_file_name(name))
    }

    /// Begin defining a stub tool. Chain setters, then call
    /// [`ToolSpec::install`].
    pub fn tool<'a>(&'a self, name: &str) -> ToolSpec<'a> {
        ToolSpec {
            dir: self,
            name: name.to_string(),
            stdout: String::new(),
            stderr: String::new(),
            exit: 0,
            script: None,
            creates: Vec::new(),
        }
    }

    /// Prepend [`bin_dir`](Self::bin_dir) to `PATH` for hard-coded tool names.
    ///
    /// Returns a guard that restores the prior `PATH` and releases the env mutex
    /// when dropped. The test **must** be `#[serial]`; the guard holds the
    /// shared [`env_mutex`] so it cannot race other env-mutating tests, but
    /// `#[serial]` is still required because coverage runs share one process.
    pub fn activate(&self) -> PathGuard {
        let lock = env_mutex().lock().unwrap_or_else(|e| e.into_inner());
        let prior = std::env::var_os("PATH");
        let mut entries: Vec<PathBuf> = vec![self.dir.path().to_path_buf()];
        if let Some(ref p) = prior {
            entries.extend(std::env::split_paths(p));
        }
        let joined = std::env::join_paths(entries).expect("fake_tool: join PATH");
        // PATH is resolved by spawned children via execvp(3), not through any
        // injectable EnvSource, so binary-stub tests must mutate the real
        // process PATH; env_mutex (held for the guard's life) + the documented
        // `#[serial]` caller requirement serialise it.
        PathGuard {
            _path: super::env::EnvGuard::set("PATH", &joined),
            _lock: lock,
        }
    }

    /// Every recorded invocation of `name`, outer `Vec` per call, inner `Vec`
    /// the argv (excluding arg0). Empty if the stub was never run.
    pub fn calls(&self, name: &str) -> Vec<Vec<String>> {
        let log = self.calls_path(name);
        let Ok(raw) = std::fs::read_to_string(&log) else {
            return Vec::new();
        };
        // Each invocation writes its argv terminated by REC_SEP, so the element
        // after the final terminator is always an empty tail — drop it. Every
        // remaining element is one invocation (an empty one means a zero-arg
        // call, which still counts).
        let mut records: Vec<&str> = raw.split(REC_SEP).collect();
        if records.last() == Some(&"") {
            records.pop();
        }
        records
            .iter()
            .map(|rec| {
                rec.split(ARG_SEP)
                    .filter(|a| !a.is_empty())
                    .map(|a| a.to_string())
                    .collect()
            })
            .collect()
    }

    /// Whether `name` was invoked at least once.
    pub fn was_called(&self, name: &str) -> bool {
        self.calls_path(name).exists()
    }

    /// Number of times `name` was invoked.
    pub fn call_count(&self, name: &str) -> usize {
        self.calls(name).len()
    }

    fn calls_path(&self, name: &str) -> PathBuf {
        self.dir.path().join(format!(".calls.{name}"))
    }
}

impl Default for FakeToolDir {
    fn default() -> Self {
        Self::new()
    }
}

/// Builder for a single fake tool. Created by [`FakeToolDir::tool`].
#[must_use = "call `.install()` to write the stub"]
pub struct ToolSpec<'a> {
    dir: &'a FakeToolDir,
    name: String,
    stdout: String,
    stderr: String,
    exit: i32,
    script: Option<String>,
    creates: Vec<(String, String)>,
}

impl ToolSpec<'_> {
    /// Text the stub writes to stdout.
    pub fn stdout(mut self, s: impl Into<String>) -> Self {
        self.stdout = s.into();
        self
    }

    /// Text the stub writes to stderr.
    pub fn stderr(mut self, s: impl Into<String>) -> Self {
        self.stderr = s.into();
        self
    }

    /// Exit code the stub returns (default `0`).
    pub fn exit(mut self, code: i32) -> Self {
        self.exit = code;
        self
    }

    /// Make the stub create an output file (path relative to the tool's working
    /// directory, or absolute) with the given contents before exiting. Useful
    /// for tools whose stage asserts the artifact exists (sbom, makeself, srpm).
    /// Unix only.
    pub fn creates(mut self, rel_path: impl Into<String>, contents: impl Into<String>) -> Self {
        self.creates.push((rel_path.into(), contents.into()));
        self
    }

    /// Replace the default emit-and-exit body with an arbitrary `sh` snippet,
    /// run after argv is recorded. The snippet can read `"$@"` and create files.
    /// Unix only; overrides [`stdout`](Self::stdout)/[`stderr`](Self::stderr)/
    /// [`exit`](Self::exit).
    pub fn script(mut self, body: impl Into<String>) -> Self {
        self.script = Some(body.into());
        self
    }

    /// Write the stub to disk and make it executable.
    ///
    /// # Panics
    /// Panics if the stub cannot be written or marked executable.
    pub fn install(self) {
        let path = self.dir.tool_path(&self.name);
        let calls = self.dir.calls_path(&self.name);
        let body = self.render_script(&calls);
        #[cfg(unix)]
        write_executable_script(&path, &body);
        #[cfg(not(unix))]
        {
            std::fs::write(&path, body).expect("fake_tool: write stub");
            make_executable(&path);
        }
    }

    #[cfg(unix)]
    fn render_script(&self, calls: &Path) -> String {
        let mut s = String::from("#!/bin/sh\n");
        // Record argv (excluding arg0) as ARG_SEP-joined, REC_SEP-terminated.
        // Build the whole record in one variable and emit it with a single
        // `printf` so the append is one atomic write — stages that invoke the
        // tool in parallel (e.g. makeself) append concurrently, and two
        // separate writes per call would interleave and merge records.
        s.push_str(&format!(
            "__r=''\nfor __a in \"$@\"; do __r=\"${{__r}}${{__a}}{arg}\"; done\n\
             printf '%s{rec}' \"$__r\" >> {log}\n",
            arg = ARG_SEP,
            rec = REC_SEP,
            log = crate::shell::shell_single_quote(&calls.to_string_lossy()),
        ));
        for (rel, contents) in &self.creates {
            // mkdir -p the parent so relative nested outputs work.
            s.push_str(&format!(
                "mkdir -p \"$(dirname {p})\" 2>/dev/null || true\n",
                p = crate::shell::shell_single_quote(rel)
            ));
            s.push_str(&format!(
                "printf '%s' {c} > {p}\n",
                c = crate::shell::shell_single_quote(contents),
                p = crate::shell::shell_single_quote(rel),
            ));
        }
        if let Some(custom) = &self.script {
            s.push_str(custom);
            if !custom.ends_with('\n') {
                s.push('\n');
            }
        } else {
            if !self.stdout.is_empty() {
                s.push_str(&format!(
                    "printf '%s' {}\n",
                    crate::shell::shell_single_quote(&self.stdout)
                ));
            }
            if !self.stderr.is_empty() {
                s.push_str(&format!(
                    "printf '%s' {} 1>&2\n",
                    crate::shell::shell_single_quote(&self.stderr)
                ));
            }
            s.push_str(&format!("exit {}\n", self.exit));
        }
        s
    }

    #[cfg(not(unix))]
    fn render_script(&self, calls: &Path) -> String {
        assert!(
            self.script.is_none() && self.creates.is_empty(),
            "fake_tool: .script()/.creates() are unix-only"
        );
        let mut s = String::from("@echo off\r\n");
        s.push_str(&format!(">>\"{}\" echo %*\r\n", calls.display()));
        if !self.stdout.is_empty() {
            s.push_str(&format!(
                "echo|set /p=\"{}\"\r\n",
                self.stdout.replace('\n', " ")
            ));
        }
        if !self.stderr.is_empty() {
            s.push_str(&format!(
                "echo|set /p=\"{}\" 1>&2\r\n",
                self.stderr.replace('\n', " ")
            ));
        }
        s.push_str(&format!("exit /b {}\r\n", self.exit));
        s
    }
}

/// Restores `PATH` and releases the env mutex when dropped. Returned by
/// [`FakeToolDir::activate`].
///
/// Field order is the drop order: the `PATH` override is restored while the
/// env mutex is still held.
pub struct PathGuard {
    _path: super::env::EnvGuard,
    _lock: std::sync::MutexGuard<'static, ()>,
}

#[cfg(unix)]
fn stub_file_name(name: &str) -> String {
    name.to_string()
}

#[cfg(not(unix))]
fn stub_file_name(name: &str) -> String {
    format!("{name}.cmd")
}

#[cfg(unix)]
fn make_executable(path: &Path) {
    use std::os::unix::fs::PermissionsExt;
    let mut perms = std::fs::metadata(path)
        .expect("fake_tool: stat stub")
        .permissions();
    perms.set_mode(0o755);
    std::fs::set_permissions(path, perms).expect("fake_tool: chmod stub");
}

#[cfg(not(unix))]
fn make_executable(_path: &Path) {}

/// Marker env var that makes a script written by [`write_executable_script`]
/// exit before its body runs.
#[cfg(unix)]
const EXEC_PROBE_VAR: &str = "ANODIZER_FAKE_TOOL_PROBE";

/// Write `script` to `path` as an executable file, returning only once the
/// file can actually be exec'd.
///
/// Every test that writes an executable and then spawns it goes through here.
/// `execve` refuses a file any process still holds open for writing
/// (`ETXTBSY`), and a sibling test thread that forks between this write's
/// open and its close inherits the writable descriptor until its own `exec`
/// (the descriptor is `CLOEXEC`, so the child releases it at `exec`, not at
/// `fork`). The spawn that trips over it is usually production code, which
/// has no business retrying `ETXTBSY` — so the window is drained here
/// instead, by exec'ing the script once under [`EXEC_PROBE_VAR`]. A guard
/// line inserted below the shebang exits on that marker, so the probe records
/// no call and creates no file; once it succeeds the inode carries no writer
/// anywhere, and the caller's real spawn cannot see `ETXTBSY`.
///
/// A leading `#!` line is preserved and the guard goes directly under it; a
/// script written without one gets `/bin/sh`. The guard is POSIX-shell syntax,
/// so the interpreter must be `sh`-compatible (`sh`, `bash`, `dash`, …) — a
/// stub under any other interpreter fails on the guard line, and this function
/// panics rather than hand back a stub that dies on its caller's spawn.
///
/// # Panics
/// Panics if the write fails, if the file stays `ETXTBSY`, or if the probe
/// exits any way but through the guard (status 0, nothing on stderr) — the
/// message names the path, the shebang, the status and the stderr.
#[cfg(unix)]
pub fn write_executable_script(path: &Path, script: &str) {
    let (shebang, body) = match script.starts_with("#!") {
        true => script.split_once('\n').unwrap_or((script, "")),
        false => ("#!/bin/sh", script),
    };
    let script = format!("{shebang}\nif [ -n \"${EXEC_PROBE_VAR}\" ]; then exit 0; fi\n{body}");
    std::fs::write(path, script)
        .unwrap_or_else(|e| panic!("fake_tool: write {}: {e}", path.display()));
    make_executable(path);
    for _ in 0..500 {
        match std::process::Command::new(path)
            .env(EXEC_PROBE_VAR, "1")
            .output()
        {
            Err(e) if e.kind() == std::io::ErrorKind::ExecutableFileBusy => {
                std::thread::sleep(std::time::Duration::from_millis(1));
            }
            Err(e) => panic!("fake_tool: probe {}: {e}", path.display()),
            // The guard is the only thing the probe may reach: it exits 0 and
            // writes nothing. Anything else means the body ran, or the
            // interpreter choked on the guard.
            Ok(out) if out.status.success() && out.stderr.is_empty() => return,
            Ok(out) => panic!(
                "fake_tool: {} did not exit through the probe guard \
                 (shebang {shebang:?}, status {}, stderr {:?}). The guard is \
                 POSIX-shell syntax, so the interpreter must be sh-compatible.",
                path.display(),
                out.status,
                String::from_utf8_lossy(&out.stderr),
            ),
        }
    }
    panic!(
        "fake_tool: {} still reported ETXTBSY after 500 probes",
        path.display()
    );
}

/// `Command::output` with a bounded retry on `ETXTBSY` ("Text file busy").
///
/// [`write_executable_script`] already drains that window before it returns,
/// so a stub installed through it cannot report `ETXTBSY` here. This stays as
/// the safety net for a command built from a path the caller wrote some other
/// way, and it keeps the real spawn-the-tool code path under test rather than
/// routing the stub through `sh <stub>`.
#[cfg(unix)]
pub fn output_retrying_etxtbsy(cmd: &mut std::process::Command) -> std::process::Output {
    for _ in 0..50 {
        match cmd.output() {
            Err(e) if e.kind() == std::io::ErrorKind::ExecutableFileBusy => {
                std::thread::sleep(std::time::Duration::from_millis(10));
            }
            other => return other.expect("spawn fake tool"),
        }
    }
    panic!("fake tool stayed ETXTBSY after 50 retries");
}

// Unix-only: every test here spawns a fake tool that is a shell script, so the
// whole module compiles only on unix — gating it once here keeps the Windows
// build free of unused-import warnings without per-item `#[cfg(unix)]`.
#[cfg(all(test, unix))]
mod tests {
    use super::*;
    use std::process::Command;

    #[test]
    fn records_argv_across_invocations() {
        let tools = FakeToolDir::new();
        tools.tool("widget").stdout("ok\n").install();
        let bin = tools.tool_path("widget");

        let out = output_retrying_etxtbsy(Command::new(&bin).args(["build", "--fast"]));
        assert!(out.status.success());
        assert_eq!(String::from_utf8_lossy(&out.stdout), "ok\n");
        output_retrying_etxtbsy(Command::new(&bin).arg("clean"));

        assert!(tools.was_called("widget"));
        assert_eq!(tools.call_count("widget"), 2);
        let calls = tools.calls("widget");
        assert_eq!(calls[0], vec!["build", "--fast"]);
        assert_eq!(calls[1], vec!["clean"]);
    }

    /// The guard inserted under the shebang is POSIX-shell syntax, so a stub
    /// whose interpreter cannot read it dies on its first line. The helper has
    /// to say so: returning a stub that fails on the caller's own spawn moves
    /// the failure somewhere it reads as a bug in the code under test.
    #[test]
    #[should_panic(expected = "#!/usr/bin/env python3")]
    fn a_non_shell_interpreter_fails_the_probe() {
        let dir = TempDir::new().unwrap();
        write_executable_script(
            &dir.path().join("py-stub"),
            "#!/usr/bin/env python3\nprint(\"hi\")\n",
        );
    }

    /// Any `sh`-compatible interpreter passes: the guard exits before the body,
    /// which then runs normally on the caller's own spawn.
    #[test]
    fn a_bash_shebang_passes_the_probe() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("bash-stub");
        write_executable_script(&path, "#!/bin/bash\necho body\nexit 3\n");
        let out = output_retrying_etxtbsy(&mut Command::new(&path));
        assert_eq!(out.status.code(), Some(3));
        assert_eq!(String::from_utf8_lossy(&out.stdout), "body\n");
    }

    /// A script written without a shebang runs under `/bin/sh`, so the guard
    /// runs there too.
    #[test]
    fn a_script_without_a_shebang_passes_the_probe() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("bare-stub");
        write_executable_script(&path, "echo bare\n");
        let out = output_retrying_etxtbsy(&mut Command::new(&path));
        assert_eq!(String::from_utf8_lossy(&out.stdout), "bare\n");
    }

    #[test]
    fn honors_exit_code_and_stderr() {
        let tools = FakeToolDir::new();
        tools.tool("boom").stderr("fatal\n").exit(7).install();
        let out = output_retrying_etxtbsy(&mut Command::new(tools.tool_path("boom")));
        assert_eq!(out.status.code(), Some(7));
        assert_eq!(String::from_utf8_lossy(&out.stderr), "fatal\n");
    }

    #[test]
    fn creates_output_file() {
        let tools = FakeToolDir::new();
        tools
            .tool("gen")
            .creates("out/doc.json", "{\"k\":1}")
            .install();
        let work = TempDir::new().unwrap();
        let out =
            output_retrying_etxtbsy(Command::new(tools.tool_path("gen")).current_dir(work.path()));
        assert!(out.status.success());
        let body = std::fs::read_to_string(work.path().join("out/doc.json")).unwrap();
        assert_eq!(body, "{\"k\":1}");
    }

    #[test]
    fn custom_script_sees_argv() {
        let tools = FakeToolDir::new();
        // syft-style: write the file named after the `-o fmt=PATH` arg.
        tools
            .tool("syft")
            .script("for a in \"$@\"; do case \"$a\" in *=*) echo '{}' > \"${a#*=}\";; esac; done")
            .install();
        let work = TempDir::new().unwrap();
        output_retrying_etxtbsy(
            Command::new(tools.tool_path("syft"))
                .current_dir(work.path())
                .args(["scan", "-o", "spdx-json=bom.json"]),
        );
        assert_eq!(
            std::fs::read_to_string(work.path().join("bom.json")).unwrap(),
            "{}\n"
        );
    }

    #[test]
    #[serial_test::serial(path_env)]
    fn activate_prepends_path_and_restores() {
        let before = std::env::var_os("PATH");
        let tools = FakeToolDir::new();
        tools.tool("findme").install();
        {
            let _g = tools.activate();
            let resolved = which_on_path("findme");
            assert_eq!(
                resolved.as_deref(),
                Some(tools.tool_path("findme").as_path())
            );
        }
        assert_eq!(std::env::var_os("PATH"), before);
    }

    fn which_on_path(name: &str) -> Option<PathBuf> {
        let path = std::env::var_os("PATH")?;
        std::env::split_paths(&path)
            .map(|d| d.join(name))
            .find(|p| p.exists())
    }
}