BlueGit

timfa posprint

Files

posprint / src / cli.rs

cli.rs

cli.rs 4.4 KiB Download Raw
1use std::collections::HashMap;
2use std::path::PathBuf;
3
4use clap::{Parser, Subcommand};
5
6use crate::io::PosFile;
7use crate::pipeline;
8use crate::protocol_url::{self, WARN_URL_LEN};
9
10#[derive(Parser, Debug)]
11#[command(
12 name = "posprint",
13 about = "POS print document designer",
14 disable_version_flag = false
15)]
16pub struct Cli {
17 #[command(subcommand)]
18 pub command: Option<Commands>,
19
20 /// Open the print dialog only (no editor). Exits after printing or cancel.
21 #[arg(long)]
22 pub print: bool,
23
24 /// POS template file to open in the GUI editor
25 #[arg(value_name = "FILE")]
26 pub file: Option<PathBuf>,
27}
28
29#[derive(Subcommand, Debug)]
30pub enum Commands {
31 /// Show command-line printing help (also in the GUI Help tab)
32 #[command(name = "cli-help")]
33 CliHelp,
34 /// Print a .pos file to a USB-serial printer (all parameters required)
35 Print {
36 /// Path to the `.pos` template file
37 file: PathBuf,
38 /// Serial port (e.g. COM3 on Windows, /dev/ttyUSB0 on Linux)
39 #[arg(short, long)]
40 printer: String,
41 /// Template parameter as NAME=VALUE (repeat for each `${Name}` / `$[Name]`;
42 /// checkbox params accept true/false)
43 #[arg(long = "set", value_name = "NAME=VALUE")]
44 set: Vec<String>,
45 },
46 /// Encode a `.pos` file as a `posprint://` URL (for websites / deep links)
47 Link {
48 /// Path to the `.pos` template file
49 file: PathBuf,
50 },
51}
52
53pub fn run(cli: Cli) -> i32 {
54 match cli.command {
55 Some(Commands::CliHelp) => {
56 println!("{}", crate::HELP_CLI_MARKDOWN);
57 0
58 }
59 Some(Commands::Print { file, printer, set }) => match run_print(&file, &printer, &set) {
60 Ok(()) => 0,
61 Err(e) => {
62 eprintln!("{e}");
63 1
64 }
65 },
66 Some(Commands::Link { file }) => match run_link(&file) {
67 Ok(()) => 0,
68 Err(e) => {
69 eprintln!("{e}");
70 1
71 }
72 },
73 None => {
74 eprintln!(
75 "No subcommand specified. Run `posprint --help` or start without arguments for the GUI."
76 );
77 1
78 }
79 }
80}
81
82fn run_print(file: &PathBuf, printer: &str, set: &[String]) -> Result<(), String> {
83 let params = parse_params(set)?;
84 pipeline::print_pos_file(file, printer, &params).map_err(|e| e.to_string())
85}
86
87fn run_link(file: &PathBuf) -> Result<(), String> {
88 let pos = PosFile::load_from_path(file).map_err(|e| format!("load failed: {e:?}"))?;
89 let url = protocol_url::encode_posprint_url(&pos).map_err(|e| e.to_string())?;
90 if url.len() > WARN_URL_LEN {
91 eprintln!(
92 "warning: URL is {} characters (soft limit ~{WARN_URL_LEN}). Windows may truncate protocol URLs near 8KB total command line.",
93 url.len()
94 );
95 }
96 println!("{url}");
97 Ok(())
98}
99
100pub fn parse_params(pairs: &[String]) -> Result<HashMap<String, String>, String> {
101 let mut map = HashMap::new();
102 for pair in pairs {
103 let Some((name, value)) = pair.split_once('=') else {
104 return Err(format!("invalid parameter '{pair}', expected NAME=VALUE"));
105 };
106 if name.is_empty() {
107 return Err("parameter name cannot be empty".into());
108 }
109 map.insert(name.to_string(), value.to_string());
110 }
111 Ok(map)
112}
113
114#[cfg(test)]
115mod tests {
116 use super::*;
117
118 #[test]
119 fn parses_set_pairs() {
120 let params = parse_params(&["A=1".into(), "B=two".into()]).unwrap();
121 assert_eq!(params.get("A").unwrap(), "1");
122 assert_eq!(params.get("B").unwrap(), "two");
123 }
124
125 #[test]
126 fn rejects_invalid_pair() {
127 assert!(parse_params(&["nope".into()]).is_err());
128 }
129
130 #[test]
131 fn accepts_print_flag_with_file() {
132 use clap::Parser;
133 let cli = Cli::parse_from(["posprint", "--print", "doc.pos"]);
134 assert!(cli.print);
135 assert_eq!(cli.file.as_ref().unwrap().to_str().unwrap(), "doc.pos");
136 }
137
138 #[test]
139 fn cli_help_subcommand_prints_docs() {
140 assert_eq!(
141 run(Cli {
142 command: Some(Commands::CliHelp),
143 print: false,
144 file: None,
145 }),
146 0
147 );
148 }
149}