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