use std::collections::HashMap; use std::path::PathBuf; use clap::{Parser, Subcommand}; use crate::pipeline; #[derive(Parser, Debug)] #[command( name = "posprint", about = "POS print document designer", disable_version_flag = false )] pub struct Cli { #[command(subcommand)] pub command: Option, /// Open the print dialog only (no editor). Exits after printing or cancel. #[arg(long)] pub print: bool, /// POS template file to open in the GUI editor #[arg(value_name = "FILE")] pub file: Option, } #[derive(Subcommand, Debug)] pub enum Commands { /// Show command-line printing help (also in the GUI Help tab) #[command(name = "cli-help")] CliHelp, /// Print a .pos file to a USB-serial printer (all parameters required) Print { /// Path to the `.pos` template file file: PathBuf, /// Serial port (e.g. COM3 on Windows, /dev/ttyUSB0 on Linux) #[arg(short, long)] printer: String, /// Template parameter as NAME=VALUE (repeat for each `${Name}` / `$[Name]`; /// checkbox params accept true/false) #[arg(long = "set", value_name = "NAME=VALUE")] set: Vec, }, } pub fn run(cli: Cli) -> i32 { match cli.command { Some(Commands::CliHelp) => { println!("{}", crate::HELP_CLI_MARKDOWN); 0 } Some(Commands::Print { file, printer, set }) => match run_print(&file, &printer, &set) { Ok(()) => 0, Err(e) => { eprintln!("{e}"); 1 } }, None => { eprintln!( "No subcommand specified. Run `posprint --help` or start without arguments for the GUI." ); 1 } } } fn run_print(file: &PathBuf, printer: &str, set: &[String]) -> Result<(), String> { let params = parse_params(set)?; pipeline::print_pos_file(file, printer, ¶ms).map_err(|e| e.to_string()) } pub fn parse_params(pairs: &[String]) -> Result, String> { let mut map = HashMap::new(); for pair in pairs { let Some((name, value)) = pair.split_once('=') else { return Err(format!("invalid parameter '{pair}', expected NAME=VALUE")); }; if name.is_empty() { return Err("parameter name cannot be empty".into()); } map.insert(name.to_string(), value.to_string()); } Ok(map) } #[cfg(test)] mod tests { use super::*; #[test] fn parses_set_pairs() { let params = parse_params(&["A=1".into(), "B=two".into()]).unwrap(); assert_eq!(params.get("A").unwrap(), "1"); assert_eq!(params.get("B").unwrap(), "two"); } #[test] fn rejects_invalid_pair() { assert!(parse_params(&["nope".into()]).is_err()); } #[test] fn accepts_print_flag_with_file() { use clap::Parser; let cli = Cli::parse_from(["posprint", "--print", "doc.pos"]); assert!(cli.print); assert_eq!(cli.file.as_ref().unwrap().to_str().unwrap(), "doc.pos"); } #[test] fn cli_help_subcommand_prints_docs() { assert_eq!(run(Cli { command: Some(Commands::CliHelp), print: false, file: None, }), 0); } }