//! CLI front-end for running a com straight from a binary's `main`. //! //! [`operate_com`] parses standard `--token`/`--server` arguments and hands off //! to [`run_as_com`](crate::run_as_com), so a com binary needs no arg-parsing of //! its own. use crate::{run_as_com, Com, ComError}; /// The server [`operate_com`] connects to when `--server` is omitted. pub const DEFAULT_SERVER: &str = "https://ws.stargamb.it"; /// Parse `--token`/`--server` from the process arguments and run the com. /// /// `--token ` is required. `--server ` is optional and defaults /// to [`DEFAULT_SERVER`]. `prog` is the program name shown in the usage line. /// /// On a missing token or an unrecognized argument this prints a usage message /// and exits the process with status code 2 (it never returns in that case). /// Otherwise it forwards to [`run_as_com`], which blocks indefinitely, so a /// normal return only happens on a fatal connection setup error. /// /// `factory` is called once per assigned game to build that game's [`Com`]. /// /// This is a convenience wrapper; to supply the server/token yourself (e.g. /// hard-coded or from another source), call [`run_as_com`] directly instead. pub fn operate_com(prog: &str, factory: F) -> Result<(), ComError> where F: Fn() -> B + 'static, B: Com + 'static, { let mut token: Option = None; let mut server: Option = None; let mut args = std::env::args().skip(1); while let Some(arg) = args.next() { match arg.as_str() { "--token" => token = args.next(), "--server" => server = args.next(), other => { eprintln!("error: unexpected argument '{other}'"); usage_and_exit(prog); } } } let token = token.unwrap_or_else(|| { eprintln!("error: --token is required"); usage_and_exit(prog); }); let server = server.unwrap_or_else(|| DEFAULT_SERVER.to_string()); run_as_com(&server, &token, factory) } fn usage_and_exit(prog: &str) -> ! { eprintln!("usage: {prog} --token [--server ]"); eprintln!(" --server defaults to {DEFAULT_SERVER}"); std::process::exit(2); }