BlueGit

timfa posprint

Files

posprint / src / cli.rs

cli.rs

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