OXYGENHUB
# af8cf879d4fb oxygenflow / crates / flow / src / main.rs
22.6 KiB · Rust · last changed Allow-listed egress over vsock: network "egress" { allow "host"... } 20 days ago source blame history raw
1
//! `flow`: check pipelines, run them locally, and run jobs for OxygenHub
2
//! (docs/spec.md, docs/m0.md).
3
4
mod cache;
5
mod cpio;
6
mod egress;
7
mod facts;
8
/// The job-starting code `flow-init` uses in a microVM, shared with the
9
/// syscall tier.
10
#[path = "../../flow-init/src/job.rs"]
11
mod guest;
12
mod home;
13
mod images;
14
mod microvm;
15
mod outputs;
16
mod runner;
17
mod swarm;
18
mod syscall;
19
mod wait;
20
mod workspace;
21
22
use anyhow::{bail, Context, Result};
23
use clap::{Parser, Subcommand};
24
use flow_core::api::Record;
25
use flow_core::{Pipeline, Runtime, PIPELINE_PATH};
26
use home::Home;
27
use std::collections::BTreeSet;
28
use std::path::{Path, PathBuf};
29
use std::time::Duration;
30
31
#[derive(Parser)]
32
#[command(name = "flow", version = env!("OXY_VERSION_LONG"), about = "OxygenFlow: hermetic pipelines for Oxygen repositories")]
33
struct Cli {
34
    /// The Flow home (default $FLOW_HOME, else ~/.local/share/flow).
35
    #[arg(long, global = true)]
36
    home: Option<PathBuf>,
37
    #[command(subcommand)]
38
    cmd: Cmd,
39
}
40
41
#[derive(Subcommand)]
42
enum RunnerCmd {
43
    /// Register this runner with a hub using a one-time token from its Admin → Runners page
44
    Register {
45
        /// The hub, e.g. https://earth.example:7343
46
        hub: String,
47
        /// The registration token (read from stdin when not given)
48
        #[arg(long)]
49
        token: Option<String>,
50
        /// The runner's name (default: the host name)
51
        #[arg(long)]
52
        name: Option<String>,
53
        /// The hub's CA certificate, when self-signed
54
        #[arg(long)]
55
        ca: Option<PathBuf>,
56
        /// A label the runner offers (repeatable)
57
        #[arg(long)]
58
        label: Vec<String>,
59
    },
60
    /// Measure this machine as a runner does: its speed score (100 on the
61
    /// reference machine) and class, free disk and load (spec §11.1)
62
    Bench,
63
}
64
65
#[derive(Subcommand)]
66
enum Cmd {
67
    /// Validate a pipeline and print its jobs and hash
68
    Check {
69
        /// The pipeline file (default: .flow/pipeline.kdl)
70
        file: Option<PathBuf>,
71
    },
72
    /// Print a file's BLAKE3, for pinning in flow.toml
73
    Hash { file: PathBuf },
74
    /// Rootfs images for sandboxes
75
    Rootfs {
76
        #[command(subcommand)]
77
        cmd: RootfsCmd,
78
    },
79
    /// Run the pipeline on this directory's files, locally
80
    Run {
81
        /// Only these jobs (and what they depend on)
82
        jobs: Vec<String>,
83
        /// The directory to build (default: the current one)
84
        #[arg(long, default_value = ".")]
85
        dir: PathBuf,
86
        /// Minutes before a job is stopped
87
        #[arg(long, default_value_t = 60)]
88
        timeout: u64,
89
        /// A variable for every job, as the hub's settings would give it;
90
        /// the pipeline's own `env` wins
91
        #[arg(long = "var", value_name = "NAME=VALUE")]
92
        vars: Vec<String>,
93
        /// A secret a job's `secret` block names, as the hub would supply
94
        /// it; mounted as a file, never in the environment
95
        #[arg(long = "secret", value_name = "NAME=VALUE")]
96
        secrets: Vec<String>,
97
    },
98
    /// Claim and run jobs for the hub in flow.toml's [runner] (or the
99
    /// runner.toml `flow runner register` wrote)
100
    Runner {
101
        #[command(subcommand)]
102
        cmd: Option<RunnerCmd>,
103
    },
104
    /// Follow the checks of a pushed state on OxygenHub until they finish:
105
    /// exit 0 when all passed, 1 when one failed, 2 at the time limit.
106
    /// Uses $OXY_TOKEN and $OXY_CA as oxy does.
107
    Wait {
108
        /// The repository's URL on the hub (https://hub/owner/name)
109
        url: String,
110
        /// The state hash the push moved the bookmark to (`oxy push --json` prints it)
111
        state: String,
112
        /// Minutes to wait at most
113
        #[arg(long, default_value_t = 60)]
114
        timeout: u64,
115
    },
116
    /// Show which isolation tiers this machine can run jobs in, and why
117
    /// the others cannot
118
    Tiers,
119
    /// The syscall tier's sandbox helper, started by the runner for each job
120
    #[command(name = "__sandbox", hide = true)]
121
    Sandbox { spec: PathBuf },
122
    /// Check that this machine can run the syscall tier
123
    #[command(name = "__sandbox-probe", hide = true)]
124
    SandboxProbe,
125
}
126
127
#[derive(Subcommand)]
128
enum RootfsCmd {
129
    /// Make an ext4 rootfs image from a root file system tarball and store it by hash
130
    Import {
131
        tarball: PathBuf,
132
        /// Refuse the tarball unless its SHA-256 matches (as its publisher states it)
133
        #[arg(long)]
134
        sha256: Option<String>,
135
        /// The image's own environment, NAME=value (repeatable): what a
136
        /// Dockerfile's ENV sets and `docker export` loses. Jobs start from
137
        /// it; their sandbox's and their own `env` override it
138
        #[arg(long = "env", value_name = "NAME=VALUE")]
139
        env: Vec<String>,
140
    },
141
    /// List the images this home holds
142
    List,
143
    /// Send an image to a hub, so its runners fetch it instead of having it
144
    /// copied to them: only the chunks the hub lacks travel. Uses
145
    /// $OXY_TOKEN (a token that may write repositories) and $OXY_CA
146
    Push {
147
        /// The image's hash, as pipelines pin it (cas://blob/HASH)
148
        hash: String,
149
        /// The hub (default: the runner's, from runner.toml or flow.toml)
150
        #[arg(long)]
151
        hub: Option<String>,
152
    },
153
    /// Fetch an image a hub holds into this home, as a runner does for a
154
    /// job whose image it lacks. Uses $OXY_TOKEN and $OXY_CA
155
    Pull {
156
        hash: String,
157
        #[arg(long)]
158
        hub: Option<String>,
159
    },
160
}
161
162
fn main() {
163
    let cli = Cli::parse();
164
    if let Err(e) = run(cli) {
165
        eprintln!("flow: {e:#}");
166
        std::process::exit(1);
167
    }
168
}
169
170
fn run(cli: Cli) -> Result<()> {
171
    match cli.cmd {
172
        Cmd::Sandbox { spec } => std::process::exit(syscall::sandbox_main(&spec)),
173
        Cmd::SandboxProbe => std::process::exit(syscall::probe_main()),
174
        Cmd::Check { file } => check(&file.unwrap_or_else(|| PathBuf::from(PIPELINE_PATH))),
175
        Cmd::Hash { file } => {
176
            println!("{}", home::hash_file(&file)?);
177
            Ok(())
178
        }
179
        Cmd::Rootfs { cmd } => {
180
            let home = Home::locate(cli.home.as_deref())?;
181
            match cmd {
182
                RootfsCmd::Import { tarball, sha256, env } => rootfs_import(&home, &tarball, sha256.as_deref(), &env),
183
                RootfsCmd::Push { hash, hub } => {
184
                    let client = image_client(&home, hub)?;
185
                    eprintln!("Sending image {} …", &hash[..12.min(hash.len())]);
186
                    let m = client.push(&home, &hash)?;
187
                    println!(
188
                        "Sent image {}: {} chunks the hub lacked, {} in {:.1} s",
189
                        &hash[..12],
190
                        m.chunks,
191
                        images::human(m.bytes),
192
                        m.elapsed.as_secs_f64()
193
                    );
194
                    Ok(())
195
                }
196
                RootfsCmd::Pull { hash, hub } => {
197
                    let client = image_client(&home, hub)?;
198
                    match client.fetch(&home, &hash)? {
199
                        Some(m) => {
200
                            println!(
201
                                "Fetched image {}: {} chunks, {} in {:.1} s",
202
                                &hash[..12],
203
                                m.chunks,
204
                                images::human(m.bytes),
205
                                m.elapsed.as_secs_f64()
206
                            );
207
                            Ok(())
208
                        }
209
                        None => anyhow::bail!("the hub does not hold image {}; send it with flow rootfs push", &hash[..12.min(hash.len())]),
210
                    }
211
                }
212
                RootfsCmd::List => {
213
                    for e in std::fs::read_dir(home.root.join("cas"))?.flatten() {
214
                        let size = e.metadata().map(|m| m.len()).unwrap_or(0);
215
                        if let Some(h) = e.file_name().to_string_lossy().strip_suffix(".ext4") {
216
                            println!("cas://blob/{h}  {} MiB", size >> 20);
217
                        }
218
                    }
219
                    Ok(())
220
                }
221
            }
222
        }
223
        Cmd::Run { jobs, dir, timeout, vars, secrets } => {
224
            let home = Home::locate(cli.home.as_deref())?;
225
            let pairs = |what: &str, list: &[String]| {
226
                list.iter()
227
                    .map(|e| {
228
                        e.split_once('=')
229
                            .map(|(k, v)| (k.to_string(), v.to_string()))
230
                            .ok_or_else(|| anyhow::anyhow!("--{what} {e:?}: expected NAME=VALUE"))
231
                    })
232
                    .collect::<Result<Vec<_>>>()
233
            };
234
            let (vars, secrets) = (pairs("var", &vars)?, pairs("secret", &secrets)?);
235
            run_local(&home, &dir, &jobs, Duration::from_secs(timeout * 60), &vars, &secrets)
236
        }
237
        Cmd::Runner { cmd: Some(RunnerCmd::Bench) } => {
238
            let home = Home::locate(cli.home.as_deref())?;
239
            let (speed, ms) = facts::bench();
240
            let f = facts::now(&home, Some(speed));
241
            println!("speed {speed} (class {}), benchmark {ms} ms", flow_core::api::Facts::class_of(speed));
242
            println!("free disk {} MiB at {}", f.free_disk_mib.unwrap_or(0), home.root.display());
243
            println!("load {:.2}", f.load_x100.unwrap_or(0) as f64 / 100.0);
244
            if let Some(k) = f.kernel {
245
                println!("kernel {k}");
246
            }
247
            Ok(())
248
        }
249
        Cmd::Runner { cmd: Some(RunnerCmd::Register { hub, token, name, ca, label }) } => {
250
            let home = Home::locate(cli.home.as_deref())?;
251
            if std::env::var_os("OXY_HOME").is_none() {
252
                std::env::set_var("OXY_HOME", home.root.join("oxy"));
253
            }
254
            let name = name.unwrap_or_else(|| {
255
                std::fs::read_to_string("/etc/hostname").map(|h| h.trim().to_string()).unwrap_or_else(|_| "flow".into())
256
            });
257
            let token = match token {
258
                Some(t) => t,
259
                None => {
260
                    eprintln!("Paste the registration token from the hub's Admin → Runners, then press Enter:");
261
                    let mut line = String::new();
262
                    std::io::stdin().read_line(&mut line)?;
263
                    line.trim().to_string()
264
                }
265
            };
266
            let got = runner::register(&home, &hub, &token, &name, ca, label)?;
267
            println!("registered as {} (runner {}); start it with `flow runner`", got.name, got.id);
268
            Ok(())
269
        }
270
        Cmd::Runner { cmd: None } => {
271
            let home = Home::locate(cli.home.as_deref())?;
272
            // The runner's oxy state (identity, user config) stays in its home.
273
            if std::env::var_os("OXY_HOME").is_none() {
274
                std::env::set_var("OXY_HOME", home.root.join("oxy"));
275
            }
276
            runner::serve(&home)
277
        }
278
        Cmd::Tiers => {
279
            let home = Home::locate(cli.home.as_deref())?;
280
            match runner::tiers(&home) {
281
                Ok((have, missing)) => {
282
                    for t in have {
283
                        println!("{t}: available");
284
                    }
285
                    for why in missing {
286
                        println!("{}", why.replacen(": ", ": unavailable: ", 1));
287
                    }
288
                }
289
                Err(why) => println!("{why}"),
290
            }
291
            Ok(())
292
        }
293
        Cmd::Wait { url, state, timeout } => {
294
            let token = std::env::var("OXY_TOKEN").ok();
295
            let ca = std::env::var_os("OXY_CA").map(PathBuf::from);
296
            let code =
297
                wait::wait(&url, &state, token.as_deref(), ca.as_deref(), Duration::from_secs(timeout * 60), Duration::from_secs(15))?;
298
            std::process::exit(code);
299
        }
300
    }
301
}
302
303
/// The hub image commands talk to: `--hub`, else the runner's; with
304
/// $OXY_TOKEN, else the runner's own token.
305
fn image_client(home: &Home, hub: Option<String>) -> Result<images::Client> {
306
    let runner = home.config.runner.clone();
307
    let hub = hub.or_else(|| runner.as_ref().map(|r| r.hub.clone())).context("name the hub with --hub https://HUB")?;
308
    let token = std::env::var("OXY_TOKEN")
309
        .ok()
310
        .or_else(|| runner.as_ref().map(|r| r.token.clone()))
311
        .context("set OXY_TOKEN to a token of yours on the hub")?;
312
    let ca = std::env::var_os("OXY_CA").map(PathBuf::from).or_else(|| runner.as_ref().and_then(|r| r.ca.clone()));
313
    images::Client::new(&hub, &token, ca.as_deref())
314
}
315
316
fn load(file: &Path) -> Result<Pipeline> {
317
    let src = std::fs::read_to_string(file).with_context(|| format!("read {}", file.display()))?;
318
    Pipeline::parse(&src).map_err(|p| anyhow::anyhow!("{} is not valid:\n{p}", file.display()))
319
}
320
321
fn check(file: &Path) -> Result<()> {
322
    let p = load(file)?;
323
    let depths = p.depths();
324
    for j in p.order() {
325
        let sb = &p.sandboxes[&j.sandbox];
326
        let after = if j.depends_on.is_empty() { String::new() } else { format!(" after {}", j.depends_on.join(", ")) };
327
        println!("{}{}  {} [{}]{after}", "  ".repeat(depths[j.name.as_str()]), j.name, j.exec.join(" "), sb.runtime.as_str());
328
    }
329
    println!("pipeline {}", hex::encode(p.hash()));
330
    Ok(())
331
}
332
333
/// The image environment file flow-init reads (`/etc/flow/env`): one
334
/// `NAME=value` per line, names checked as a pipeline's are.
335
fn image_env_file(env: &[String]) -> Result<String> {
336
    let mut out = String::new();
337
    for e in env {
338
        let Some((k, v)) = e.split_once('=') else { bail!("--env {e:?}: expected NAME=value") };
339
        let ok = !k.is_empty() && !k.starts_with(|c: char| c.is_ascii_digit()) && k.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_');
340
        if !ok || v.contains('\n') || v.contains('\0') {
341
            bail!("--env {e:?}: a name is letters, digits and _, and a value is one line");
342
        }
343
        out.push_str(&format!("{k}={v}\n"));
344
    }
345
    Ok(out)
346
}
347
348
/// The architecture an ELF file was built for, by its header.
349
fn elf_arch(path: &Path) -> Option<&'static str> {
350
    let bytes = std::fs::read(path).ok()?;
351
    if bytes.len() < 20 || &bytes[..4] != b"\x7fELF" {
352
        return None;
353
    }
354
    let little = bytes[5] == 1;
355
    let machine = if little { u16::from_le_bytes([bytes[18], bytes[19]]) } else { u16::from_be_bytes([bytes[18], bytes[19]]) };
356
    Some(match machine {
357
        0x3E => "x86_64",
358
        0xB7 => "aarch64",
359
        0xF3 => "riscv64",
360
        0x03 => "x86",
361
        0x28 => "arm",
362
        0x15 => "powerpc64",
363
        0x16 => "s390x",
364
        _ => return None,
365
    })
366
}
367
368
/// The architecture of an unpacked rootfs: its shell's, or the first
369
/// program's found under bin.
370
fn tree_arch(tree: &Path) -> Option<&'static str> {
371
    for rel in ["bin/sh", "bin/busybox", "usr/bin/env", "bin/bash", "usr/bin/sh"] {
372
        let p = tree.join(rel);
373
        let p = std::fs::canonicalize(&p).unwrap_or(p);
374
        if let Some(a) = elf_arch(&p) {
375
            return Some(a);
376
        }
377
    }
378
    None
379
}
380
381
fn rootfs_import(home: &Home, tarball: &Path, sha256: Option<&str>, env: &[String]) -> Result<()> {
382
    let env_file = image_env_file(env)?;
383
    if let Some(want) = sha256 {
384
        let out = std::process::Command::new("sha256sum").arg(tarball).output().context("run sha256sum")?;
385
        let got = String::from_utf8_lossy(&out.stdout).split_whitespace().next().unwrap_or("").to_string();
386
        if got != want.to_lowercase() {
387
            bail!("{} has SHA-256 {got}, expected {want}", tarball.display());
388
        }
389
    }
390
    let tmp = home.root.join("work").join(format!("rootfs-{}", std::process::id()));
391
    let _ = std::fs::remove_dir_all(&tmp);
392
    let tree = tmp.join("tree");
393
    std::fs::create_dir_all(&tree)?;
394
    let result = (|| -> Result<String> {
395
        let status = std::process::Command::new("tar").arg("-xf").arg(tarball).arg("-C").arg(&tree).arg("--no-same-owner").status()?;
396
        if !status.success() {
397
            bail!("tar could not unpack {}", tarball.display());
398
        }
399
        // The image's architecture must be this machine's: there is no
400
        // emulation tier (spec §11.2).
401
        let arch = tree_arch(&tree).unwrap_or("unknown");
402
        if arch != "unknown" && arch != std::env::consts::ARCH {
403
            bail!(
404
                "{} is a {arch} image; this runner is {}, and jobs here run no other architecture",
405
                tarball.display(),
406
                std::env::consts::ARCH
407
            );
408
        }
409
        // Mount points flow-init needs (docs/m0.md §2).
410
        for d in ["src", "tmp", "proc", "dev", "run"] {
411
            std::fs::create_dir_all(tree.join(d))?;
412
        }
413
        if !env_file.is_empty() {
414
            std::fs::create_dir_all(tree.join("etc/flow"))?;
415
            std::fs::write(tree.join("etc/flow/env"), &env_file)?;
416
        }
417
        let used: u64 = ignore::WalkBuilder::new(&tree)
418
            .hidden(false)
419
            .ignore(false)
420
            .git_ignore(false)
421
            .build()
422
            .flatten()
423
            .filter_map(|e| e.metadata().ok())
424
            .map(|m| m.len().max(4096))
425
            .sum();
426
        let mib = used * 13 / 10 / (1 << 20) + 64;
427
        let img = tmp.join("rootfs.ext4");
428
        let status = std::process::Command::new("mkfs.ext4")
429
            .args(["-q", "-F", "-L", "rootfs", "-E", "root_owner=0:0", "-d"])
430
            .arg(&tree)
431
            .arg(&img)
432
            .arg(format!("{mib}M"))
433
            .status()
434
            .context("run mkfs.ext4")?;
435
        if !status.success() {
436
            bail!("mkfs.ext4 failed");
437
        }
438
        let hash = home::hash_file(&img)?;
439
        std::fs::rename(&img, home.rootfs(&hash))?;
440
        let manifest = serde_json::json!({ "arch": if arch == "unknown" { std::env::consts::ARCH } else { arch }, "imported_ms": std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0) });
441
        std::fs::write(home.image_manifest(&hash), manifest.to_string())?;
442
        Ok(hash)
443
    })();
444
    let _ = std::fs::remove_dir_all(&tmp);
445
    let hash = result?;
446
    println!("rootfs \"cas://blob/{hash}\"");
447
    Ok(())
448
}
449
450
fn run_local(
451
    home: &Home,
452
    dir: &Path,
453
    only: &[String],
454
    timeout: Duration,
455
    vars: &[(String, String)],
456
    secrets: &[(String, String)],
457
) -> Result<()> {
458
    let p = load(&dir.join(PIPELINE_PATH))?;
459
    // The named jobs and everything they depend on.
460
    let mut wanted: BTreeSet<String> = only.iter().cloned().collect();
461
    for name in only {
462
        if !p.jobs.contains_key(name) {
463
            bail!("no job {name:?} in the pipeline");
464
        }
465
    }
466
    if !only.is_empty() {
467
        loop {
468
            let more: Vec<String> = wanted.iter().flat_map(|j| p.jobs[j].depends_on.clone()).filter(|d| !wanted.contains(d)).collect();
469
            if more.is_empty() {
470
                break;
471
            }
472
            wanted.extend(more);
473
        }
474
    }
475
    let scratch = home.root.join("work").join(format!("local-{}", std::process::id()));
476
    let _ = std::fs::remove_dir_all(&scratch);
477
    std::fs::create_dir_all(scratch.join("tree"))?;
478
    workspace::copy_tree(dir, &scratch.join("tree"))?;
479
    let mut failed: BTreeSet<String> = BTreeSet::new();
480
    let mut worst = 0;
481
    for job in p.order() {
482
        if !only.is_empty() && !wanted.contains(&job.name) {
483
            continue;
484
        }
485
        if let Some(d) = job.depends_on.iter().find(|d| failed.contains(*d)) {
486
            println!("── {} skipped: {d} failed", job.name);
487
            failed.insert(job.name.clone());
488
            continue;
489
        }
490
        let sb = &p.sandboxes[&job.sandbox];
491
        if sb.runtime == Runtime::Wasm {
492
            bail!("job {}: runtime {} is not available in this build yet", job.name, sb.runtime.as_str());
493
        }
494
        println!("── {} ({})", job.name, job.exec.join(" "));
495
        let js = scratch.join(&job.name);
496
        std::fs::create_dir_all(&js)?;
497
        let job = &job
498
            .in_sandbox(sb)
499
            .with_flow_env(&[("FLOW_JOB".into(), job.name.clone()), ("FLOW_RUN".into(), "local".into())])
500
            .with_flow_env(vars);
501
        // Identities come from a hub: a local run has none.
502
        for i in &job.identities {
503
            println!("── {}: identity {:?} is not available locally; {} will be missing", job.name, i.audience, i.mount_path);
504
        }
505
        // Each secret the job declares must be given, as the hub would.
506
        let inputs = job
507
            .secrets
508
            .iter()
509
            .map(|s| {
510
                let value = secrets.iter().find(|(k, _)| *k == s.name).map(|(_, v)| v.clone());
511
                value
512
                    .map(|value| flow_core::api::SecretInput { name: s.name.clone(), path: s.mount_path.clone(), value })
513
                    .ok_or_else(|| anyhow::anyhow!("job {}: secret {:?} is not given; pass --secret {}=VALUE", job.name, s.name, s.name))
514
            })
515
            .collect::<Result<Vec<_>>>()?;
516
        // Each job starts from the same files: jobs do not share writes.
517
        let out = if sb.runtime == Runtime::Syscall {
518
            workspace::copy_tree(&scratch.join("tree"), &js.join("tree"))?;
519
            let group = format!("local-{}-{}", std::process::id(), js.file_name().unwrap_or_default().to_string_lossy());
520
            syscall::run(home, sb, job, &inputs, &js.join("tree"), &js, timeout, &mut |r: Record| print_record(&r), &group)?
521
        } else {
522
            workspace::image(&scratch.join("tree"), &js.join("workspace.ext4"))?;
523
            microvm::run(home, sb, job, &inputs, &js.join("workspace.ext4"), &js, timeout, &mut |r: Record| print_record(&r))?
524
        };
525
        let _ = workspace::remove_tree(&js);
526
        match out.exit_code {
527
            Some(0) => println!("── {} passed in {} ms", job.name, out.duration_ms),
528
            other => {
529
                println!(
530
                    "── {} failed ({}) in {} ms",
531
                    job.name,
532
                    other.map(|c| format!("exit {c}")).unwrap_or_else(|| "no exit code".into()),
533
                    out.duration_ms
534
                );
535
                failed.insert(job.name.clone());
536
                worst = 1;
537
            }
538
        }
539
    }
540
    let _ = workspace::remove_tree(&scratch);
541
    if worst != 0 {
542
        std::process::exit(worst);
543
    }
544
    Ok(())
545
}
546
547
fn print_record(r: &Record) {
548
    match r.stream.as_str() {
549
        "out" => println!("   {}", r.text),
550
        "err" => eprintln!("   {}", r.text),
551
        s => eprintln!("   [{s}] {}", r.text),
552
    }
553
}
554
555
#[cfg(test)]
556
mod tests {
557
    use super::image_env_file;
558
559
    #[test]
560
    fn image_environments_are_checked_lines() {
561
        let f = image_env_file(&["PATH=/opt/bin:/usr/bin".into(), "X16EMU=/opt/x16emu".into(), "EMPTY=".into()]).unwrap();
562
        assert_eq!(f, "PATH=/opt/bin:/usr/bin\nX16EMU=/opt/x16emu\nEMPTY=\n");
563
        assert!(image_env_file(&["NOEQUALS".into()]).is_err());
564
        assert!(image_env_file(&["1X=y".into()]).is_err());
565
        assert!(image_env_file(&["X=two\nlines".into()]).is_err());
566
        assert_eq!(image_env_file(&[]).unwrap(), "");
567
    }
568
}