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