BlueGit

timfa posprint

Files

posprint / src / cli.rs

cli.rs

feat: include paired Classic Bluetooth SPP printers in discovery
timfa project_84475926_bot_3b4fb417c41b9b24a7422b6452f025d2 · pushed by timfa · 8 weeks ago
8b514b7f History
cli.rs 5.2 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 /// List discovered printers (USB, spooler, USB-serial, paired Bluetooth SPP)
35 List,
36 /// Print a .pos file to a printer (all parameters required)
37 Print {
38 /// Path to the `.pos` template file
39 file: PathBuf,
40 /// Printer: serial/COM, /dev/rfcomm*, USB id from `list`, or Windows queue
41 #[arg(short, long)]
42 printer: String,
43 /// Template parameter as NAME=VALUE (repeat for each `${Name}` / `$[Name]`;
44 /// checkbox params accept true/false)
45 #[arg(long = "set", value_name = "NAME=VALUE")]
46 set: Vec<String>,
47 },
48 /// Encode a `.pos` file as a `posprint://` URL (for websites / deep links)
49 Link {
50 /// Path to the `.pos` template file
51 file: PathBuf,
52 },
53}
54
55pub fn run(cli: Cli) -> i32 {
56 match cli.command {
57 Some(Commands::CliHelp) => {
58 println!("{}", crate::HELP_CLI_MARKDOWN);
59 0
60 }
61 Some(Commands::List) => match run_list() {
62 Ok(()) => 0,
63 Err(e) => {
64 eprintln!("{e}");
65 1
66 }
67 },
68 Some(Commands::Print { file, printer, set }) => match run_print(&file, &printer, &set) {
69 Ok(()) => 0,
70 Err(e) => {
71 eprintln!("{e}");
72 1
73 }
74 },
75 Some(Commands::Link { file }) => match run_link(&file) {
76 Ok(()) => 0,
77 Err(e) => {
78 eprintln!("{e}");
79 1
80 }
81 },
82 None => {
83 eprintln!(
84 "No subcommand specified. Run `posprint --help` or start without arguments for the GUI."
85 );
86 1
87 }
88 }
89}
90
91fn run_list() -> Result<(), String> {
92 let printers = crate::print::list_printers().map_err(|e| format!("{e:?}"))?;
93 if printers.is_empty() {
94 println!("No printers found.");
95 return Ok(());
96 }
97 for printer in printers {
98 println!("{}\t{}", printer.id, printer.display_name);
99 }
100 Ok(())
101}
102
103fn run_print(file: &PathBuf, printer: &str, set: &[String]) -> Result<(), String> {
104 let params = parse_params(set)?;
105 pipeline::print_pos_file(file, printer, &params).map_err(|e| e.to_string())
106}
107
108fn run_link(file: &PathBuf) -> Result<(), String> {
109 let pos = PosFile::load_from_path(file).map_err(|e| format!("load failed: {e:?}"))?;
110 let url = protocol_url::encode_posprint_url(&pos).map_err(|e| e.to_string())?;
111 if url.len() > WARN_URL_LEN {
112 eprintln!(
113 "warning: URL is {} characters (soft limit ~{WARN_URL_LEN}). Windows may truncate protocol URLs near 8KB total command line.",
114 url.len()
115 );
116 }
117 println!("{url}");
118 Ok(())
119}
120
121pub fn parse_params(pairs: &[String]) -> Result<HashMap<String, String>, String> {
122 let mut map = HashMap::new();
123 for pair in pairs {
124 let Some((name, value)) = pair.split_once('=') else {
125 return Err(format!("invalid parameter '{pair}', expected NAME=VALUE"));
126 };
127 if name.is_empty() {
128 return Err("parameter name cannot be empty".into());
129 }
130 map.insert(name.to_string(), value.to_string());
131 }
132 Ok(map)
133}
134
135#[cfg(test)]
136mod tests {
137 use super::*;
138
139 #[test]
140 fn parses_set_pairs() {
141 let params = parse_params(&["A=1".into(), "B=two".into()]).unwrap();
142 assert_eq!(params.get("A").unwrap(), "1");
143 assert_eq!(params.get("B").unwrap(), "two");
144 }
145
146 #[test]
147 fn rejects_invalid_pair() {
148 assert!(parse_params(&["nope".into()]).is_err());
149 }
150
151 #[test]
152 fn accepts_print_flag_with_file() {
153 use clap::Parser;
154 let cli = Cli::parse_from(["posprint", "--print", "doc.pos"]);
155 assert!(cli.print);
156 assert_eq!(cli.file.as_ref().unwrap().to_str().unwrap(), "doc.pos");
157 }
158
159 #[test]
160 fn cli_help_subcommand_prints_docs() {
161 assert_eq!(
162 run(Cli {
163 command: Some(Commands::CliHelp),
164 print: false,
165 file: None,
166 }),
167 0
168 );
169 }
170
171 #[test]
172 fn accepts_list_subcommand() {
173 use clap::Parser;
174 let cli = Cli::parse_from(["posprint", "list"]);
175 assert!(matches!(cli.command, Some(Commands::List)));
176 }
177}