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, } #[derive(Subcommand, Debug)] pub enum Commands { /// 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} in the template) #[arg(long = "set", value_name = "NAME=VALUE")] set: Vec, }, } pub fn run(cli: Cli) -> i32 { match cli.command { 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()); } }