diff --git a/crates/mind-body/src/bin/mind-wake.rs b/crates/mind-body/src/bin/mind-wake.rs index 761c086..56385b7 100644 --- a/crates/mind-body/src/bin/mind-wake.rs +++ b/crates/mind-body/src/bin/mind-wake.rs @@ -5,13 +5,12 @@ //! mind cannot be reached or the arguments are wrong. Without `--endpoint` the //! daemon is `HUGINN_ENDPOINT`. -use std::net::SocketAddr; use std::path::Path; use std::time::Duration; -use anyhow::{Result, anyhow, bail}; -use eureka_pipeline::Slug; +use anyhow::Result; use eureka_state::HuginnClient; +use mind_body::cli::instance_and_endpoint; use mind_body::control::{CONTROL_ROOT, FileSource, control_path}; use mind_body::launch::{Ports, SystemClock, SystemdLauncher}; use mind_body::queue::HuginnMind; @@ -22,25 +21,6 @@ const TIMEOUT: Duration = Duration::from_secs(15); const USAGE: &str = "usage: mind-wake --instance [--endpoint rudp://:]"; -/// The instance and the endpoint as given. A flag given twice or an unknown -/// argument is refused without printing it. -fn parse(args: &[String]) -> Result<(Slug, Option)> { - let (mut instance, mut endpoint) = (None, None); - let mut rest = args.iter(); - while let Some(flag) = rest.next() { - let slot = match flag.as_str() { - "--instance" => &mut instance, - "--endpoint" => &mut endpoint, - _ => bail!("{USAGE}"), - }; - let value = rest.next().ok_or_else(|| anyhow!("{USAGE}"))?; - if slot.replace(value.clone()).is_some() { - bail!("{USAGE}"); - } - } - Ok((Slug(instance.ok_or_else(|| anyhow!("{USAGE}"))?), endpoint)) -} - /// The host a run records: the kernel's name for this machine. fn host() -> String { std::fs::read_to_string("/proc/sys/kernel/hostname").map(|name| name.trim().to_string()).ok().filter(|name| !name.is_empty()).unwrap_or_else(|| "unknown".into()) @@ -51,13 +31,8 @@ fn host() -> String { #[allow(clippy::disallowed_methods, reason = "the binary reads its own arguments and the daemon's address, and hands them to the library")] fn run() -> Result { let args: Vec = std::env::args().skip(1).collect(); - let (instance, endpoint) = parse(&args)?; + let (instance, address) = instance_and_endpoint(&args, std::env::var("HUGINN_ENDPOINT").ok(), USAGE)?; let source = FileSource::new(control_path(Path::new(CONTROL_ROOT), &instance)?); - let endpoint = endpoint.or_else(|| std::env::var("HUGINN_ENDPOINT").ok()).ok_or_else(|| anyhow!("no daemon endpoint: --endpoint or HUGINN_ENDPOINT"))?; - let address = endpoint - .strip_prefix("rudp://") - .and_then(|address| address.parse::().ok()) - .ok_or_else(|| anyhow!("the endpoint is not rudp://:"))?; let mind = HuginnMind::new(HuginnClient::new(address, instance, TIMEOUT)); let launcher = SystemdLauncher::new(); let host = host(); diff --git a/crates/mind-body/src/cli.rs b/crates/mind-body/src/cli.rs index edd59aa..81d531e 100644 --- a/crates/mind-body/src/cli.rs +++ b/crates/mind-body/src/cli.rs @@ -18,6 +18,7 @@ //! fails if either step failed. No other command stops anything. use std::io::Write; +use std::net::SocketAddr; use std::path::Path; use std::str::FromStr; @@ -32,6 +33,36 @@ use crate::launch::unit; const USAGE: &str = "usage: mind-control [--root ] --instance show | check | brake hold | brake release | dial set --heat H --base-cooldown-s S --base-run-usd U"; +/// The arguments every organ binary shares: `--instance ` and an optional +/// `--endpoint rudp://:`, which `env_endpoint` (the binary's reading of +/// `HUGINN_ENDPOINT`) replaces when absent. A flag given twice, an unknown +/// argument, a name that is not a slug or an endpoint that is not +/// `rudp://:` is refused with `usage` or a fixed message, and no +/// value is echoed. +pub fn instance_and_endpoint(args: &[String], env_endpoint: Option, usage: &str) -> Result<(Slug, SocketAddr)> { + let (mut instance, mut endpoint) = (None, None); + let mut rest = args.iter(); + while let Some(flag) = rest.next() { + let slot = match flag.as_str() { + "--instance" => &mut instance, + "--endpoint" => &mut endpoint, + _ => bail!("{usage}"), + }; + let value = rest.next().ok_or_else(|| anyhow!("{usage}"))?; + if slot.replace(value.clone()).is_some() { + bail!("{usage}"); + } + } + let instance = Slug(instance.ok_or_else(|| anyhow!("{usage}"))?); + instance.validate_slug().map_err(|_| anyhow!("the instance is not a slug"))?; + let endpoint = endpoint.or(env_endpoint).ok_or_else(|| anyhow!("no daemon endpoint: --endpoint or HUGINN_ENDPOINT"))?; + let address = endpoint + .strip_prefix("rudp://") + .and_then(|address| address.parse::().ok()) + .ok_or_else(|| anyhow!("the endpoint is not rudp://:"))?; + Ok((instance, address)) +} + /// Who made the change: `SUDO_USER`, else `USER`, else `unknown`. An empty /// variable counts as unset. pub fn operator_name(sudo_user: Option, user: Option) -> String { diff --git a/crates/mind-body/tests/cli.rs b/crates/mind-body/tests/cli.rs index 159efc0..fdc2105 100644 --- a/crates/mind-body/tests/cli.rs +++ b/crates/mind-body/tests/cli.rs @@ -375,3 +375,49 @@ fn the_binary_hold_fails_with_status_2_when_systemctl_does() { assert!(stderr.contains("units were not stopped") && stderr.contains("exit status 5"), "{stderr}"); assert!(!String::from_utf8_lossy(&output.stdout).contains("stopped")); } + +// ---- the arguments every organ binary shares ---- + +mod shared_arguments { + use mind_body::cli::instance_and_endpoint; + + const USAGE: &str = "usage: test-organ --instance "; + + fn parse(args: &[&str], env: Option<&str>) -> anyhow::Result<(eureka_pipeline::Slug, std::net::SocketAddr)> { + let args: Vec = args.iter().map(|a| a.to_string()).collect(); + instance_and_endpoint(&args, env.map(str::to_string), USAGE) + } + + #[test] + fn the_flag_names_the_endpoint_and_wins_over_the_environment_which_is_the_fallback() { + let (instance, address) = parse(&["--instance", "yggdrasil", "--endpoint", "rudp://10.77.0.1:17872"], Some("rudp://127.0.0.1:1")).unwrap(); + assert_eq!((instance.0.as_str(), address.to_string().as_str()), ("yggdrasil", "10.77.0.1:17872")); + let (_, address) = parse(&["--endpoint", "rudp://10.77.0.1:17872", "--instance", "yggdrasil"], None).unwrap(); + assert_eq!(address.to_string(), "10.77.0.1:17872", "flag order does not matter"); + let (_, address) = parse(&["--instance", "yggdrasil"], Some("rudp://127.0.0.1:9")).unwrap(); + assert_eq!(address.to_string(), "127.0.0.1:9"); + } + + #[test] + fn every_refusal_is_fixed_text_that_echoes_no_value() { + let canary = "canary-value-91e7"; + let cases: Vec<(Vec<&str>, Option<&str>, &str)> = vec![ + (vec![], Some("rudp://127.0.0.1:9"), USAGE), + (vec!["--instance"], None, USAGE), + (vec!["--instance", "a", "--instance", canary], Some("rudp://127.0.0.1:9"), USAGE), + (vec!["--instance", "a", "--endpoint", "rudp://127.0.0.1:9", "--endpoint", canary], None, USAGE), + (vec!["--instance", "a", canary], Some("rudp://127.0.0.1:9"), USAGE), + (vec!["--endpoint", "rudp://127.0.0.1:9"], None, USAGE), + (vec!["--instance", "Canary/../x"], Some("rudp://127.0.0.1:9"), "the instance is not a slug"), + (vec!["--instance", "a"], None, "no daemon endpoint: --endpoint or HUGINN_ENDPOINT"), + (vec!["--instance", "a", "--endpoint", canary], None, "the endpoint is not rudp://:"), + (vec!["--instance", "a", "--endpoint", "http://127.0.0.1:9"], None, "the endpoint is not rudp://:"), + (vec!["--instance", "a", "--endpoint", "rudp://not-an-address"], None, "the endpoint is not rudp://:"), + (vec!["--instance", "a"], Some(canary), "the endpoint is not rudp://:"), + ]; + for (args, env, message) in cases { + let error = parse(&args, env).unwrap_err(); + assert_eq!(format!("{error:#}"), message, "{args:?} {env:?}"); + } + } +}