| 1 | use std::collections::HashMap;
|
| 2 | use std::path::PathBuf;
|
| 3 |
|
| 4 | use clap::{Parser, Subcommand};
|
| 5 |
|
| 6 | use crate::pipeline;
|
| 7 |
|
| 8 | #[derive(Parser, Debug)]
|
| 9 | #[command(
|
| 10 | name = "posprint",
|
| 11 | about = "POS print document designer",
|
| 12 | disable_version_flag = false
|
| 13 | )]
|
| 14 | pub struct Cli {
|
| 15 | #[command(subcommand)]
|
| 16 | pub command: Option<Commands>,
|
| 17 | }
|
| 18 |
|
| 19 | #[derive(Subcommand, Debug)]
|
| 20 | pub enum Commands {
|
| 21 | /// Print a .pos file to a USB-serial printer (all parameters required)
|
| 22 | Print {
|
| 23 | /// Path to the `.pos` template file
|
| 24 | file: PathBuf,
|
| 25 | /// Serial port (e.g. COM3 on Windows, /dev/ttyUSB0 on Linux)
|
| 26 | #[arg(short, long)]
|
| 27 | printer: String,
|
| 28 | /// Template parameter as NAME=VALUE (repeat for each ${Name} in the template)
|
| 29 | #[arg(long = "set", value_name = "NAME=VALUE")]
|
| 30 | set: Vec<String>,
|
| 31 | },
|
| 32 | }
|
| 33 |
|
| 34 | pub fn run(cli: Cli) -> i32 {
|
| 35 | match cli.command {
|
| 36 | Some(Commands::Print { file, printer, set }) => match run_print(&file, &printer, &set) {
|
| 37 | Ok(()) => 0,
|
| 38 | Err(e) => {
|
| 39 | eprintln!("{e}");
|
| 40 | 1
|
| 41 | }
|
| 42 | },
|
| 43 | None => {
|
| 44 | eprintln!("No subcommand specified. Run `posprint --help` or start without arguments for the GUI.");
|
| 45 | 1
|
| 46 | }
|
| 47 | }
|
| 48 | }
|
| 49 |
|
| 50 | fn run_print(file: &PathBuf, printer: &str, set: &[String]) -> Result<(), String> {
|
| 51 | let params = parse_params(set)?;
|
| 52 | pipeline::print_pos_file(file, printer, ¶ms).map_err(|e| e.to_string())
|
| 53 | }
|
| 54 |
|
| 55 | pub fn parse_params(pairs: &[String]) -> Result<HashMap<String, String>, String> {
|
| 56 | let mut map = HashMap::new();
|
| 57 | for pair in pairs {
|
| 58 | let Some((name, value)) = pair.split_once('=') else {
|
| 59 | return Err(format!("invalid parameter '{pair}', expected NAME=VALUE"));
|
| 60 | };
|
| 61 | if name.is_empty() {
|
| 62 | return Err("parameter name cannot be empty".into());
|
| 63 | }
|
| 64 | map.insert(name.to_string(), value.to_string());
|
| 65 | }
|
| 66 | Ok(map)
|
| 67 | }
|
| 68 |
|
| 69 | #[cfg(test)]
|
| 70 | mod tests {
|
| 71 | use super::*;
|
| 72 |
|
| 73 | #[test]
|
| 74 | fn parses_set_pairs() {
|
| 75 | let params = parse_params(&["A=1".into(), "B=two".into()]).unwrap();
|
| 76 | assert_eq!(params.get("A").unwrap(), "1");
|
| 77 | assert_eq!(params.get("B").unwrap(), "two");
|
| 78 | }
|
| 79 |
|
| 80 | #[test]
|
| 81 | fn rejects_invalid_pair() {
|
| 82 | assert!(parse_params(&["nope".into()]).is_err());
|
| 83 | }
|
| 84 | }
|