|
| 1 | +use anyhow::{ensure, Context, Result}; |
| 2 | +use clap::Parser; |
| 3 | +use serde::{Deserialize, Serialize}; |
| 4 | + |
| 5 | +mod cli; |
| 6 | + |
| 7 | +#[derive(Debug, Deserialize, Serialize)] |
| 8 | +#[serde(deny_unknown_fields)] |
| 9 | +pub(crate) struct ReinstallConfig { |
| 10 | + /// The bootc image to install on the system. |
| 11 | + pub(crate) bootc_image: String, |
| 12 | + |
| 13 | + /// The raw CLI arguments that were used to invoke the program. None if the config was loaded |
| 14 | + /// from a file. |
| 15 | + #[serde(skip_deserializing)] |
| 16 | + cli_flags: Option<Vec<String>>, |
| 17 | +} |
| 18 | + |
| 19 | +impl ReinstallConfig { |
| 20 | + pub fn parse_from_cli(cli: cli::Cli) -> Self { |
| 21 | + Self { |
| 22 | + bootc_image: cli.bootc_image, |
| 23 | + cli_flags: Some(std::env::args().collect::<Vec<String>>()), |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + pub fn load() -> Result<Self> { |
| 28 | + Ok(match std::env::var("BOOTC_REINSTALL_CONFIG") { |
| 29 | + Ok(config_path) => { |
| 30 | + ensure_no_cli_args()?; |
| 31 | + |
| 32 | + serde_yaml::from_slice( |
| 33 | + &std::fs::read(&config_path) |
| 34 | + .context("reading BOOTC_REINSTALL_CONFIG file {config_path}")?, |
| 35 | + ) |
| 36 | + .context("parsing BOOTC_REINSTALL_CONFIG file {config_path}")? |
| 37 | + } |
| 38 | + Err(_) => ReinstallConfig::parse_from_cli(cli::Cli::parse()), |
| 39 | + }) |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +fn ensure_no_cli_args() -> Result<()> { |
| 44 | + let num_args = std::env::args().len(); |
| 45 | + |
| 46 | + ensure!( |
| 47 | + num_args == 1, |
| 48 | + "BOOTC_REINSTALL_CONFIG is set, but there are {num_args} CLI arguments. BOOTC_REINSTALL_CONFIG is meant to be used with no arguments." |
| 49 | + ); |
| 50 | + |
| 51 | + Ok(()) |
| 52 | +} |
0 commit comments