| 1 | use std::collections::HashMap;
|
| 2 | use std::path::Path;
|
| 3 |
|
| 4 | use crate::dsl::{parse, Document};
|
| 5 | use crate::escpos::{EscPosEncoder, EscPosError};
|
| 6 | use crate::io::{LoadError, PosFile};
|
| 7 | use crate::params::{collect_parameter_names, substitute_document};
|
| 8 | use crate::print::{open_printer_by_name, print_bytes, PrintError};
|
| 9 |
|
| 10 | #[derive(Debug)]
|
| 11 | pub enum PipelineError {
|
| 12 | Load(LoadError),
|
| 13 | Parse(crate::dsl::ParseError),
|
| 14 | MissingParams(Vec<String>),
|
| 15 | Encode(EscPosError),
|
| 16 | Print(PrintError),
|
| 17 | }
|
| 18 |
|
| 19 | impl std::fmt::Display for PipelineError {
|
| 20 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
| 21 | match self {
|
| 22 | Self::Load(e) => write!(f, "{e:?}"),
|
| 23 | Self::Parse(e) => write!(f, "{e}"),
|
| 24 | Self::MissingParams(names) => {
|
| 25 | write!(f, "missing parameters: {}", names.join(", "))
|
| 26 | }
|
| 27 | Self::Encode(e) => write!(f, "{e:?}"),
|
| 28 | Self::Print(e) => write!(f, "{e:?}"),
|
| 29 | }
|
| 30 | }
|
| 31 | }
|
| 32 |
|
| 33 | impl std::error::Error for PipelineError {}
|
| 34 |
|
| 35 | pub fn missing_parameters(document: &Document, params: &HashMap<String, String>) -> Vec<String> {
|
| 36 | collect_parameter_names(document)
|
| 37 | .into_iter()
|
| 38 | .filter(|name| {
|
| 39 | params
|
| 40 | .get(name)
|
| 41 | .map(|v| v.is_empty())
|
| 42 | .unwrap_or(true)
|
| 43 | })
|
| 44 | .collect()
|
| 45 | }
|
| 46 |
|
| 47 | pub fn encode_pos_file(
|
| 48 | file: &PosFile,
|
| 49 | base_dir: Option<&Path>,
|
| 50 | params: &HashMap<String, String>,
|
| 51 | ) -> Result<Vec<u8>, PipelineError> {
|
| 52 | let doc = parse(&file.body).map_err(PipelineError::Parse)?;
|
| 53 | let missing = missing_parameters(&doc, params);
|
| 54 | if !missing.is_empty() {
|
| 55 | return Err(PipelineError::MissingParams(missing));
|
| 56 | }
|
| 57 | let sub = substitute_document(&doc, params);
|
| 58 | let mut encoder = EscPosEncoder::new(file.metadata.clone());
|
| 59 | if let Some(dir) = base_dir {
|
| 60 | encoder = encoder.with_base_dir(dir);
|
| 61 | }
|
| 62 | let bytes = encoder
|
| 63 | .encode_document(&sub)
|
| 64 | .map_err(PipelineError::Encode)?;
|
| 65 | Ok(bytes.to_vec())
|
| 66 | }
|
| 67 |
|
| 68 | pub fn print_pos_file(
|
| 69 | path: &Path,
|
| 70 | printer_port: &str,
|
| 71 | params: &HashMap<String, String>,
|
| 72 | ) -> Result<(), PipelineError> {
|
| 73 | let file = PosFile::load_from_path(path).map_err(PipelineError::Load)?;
|
| 74 | let base_dir = path.parent();
|
| 75 | let bytes = encode_pos_file(&file, base_dir, params)?;
|
| 76 | let mut transport = open_printer_by_name(printer_port).map_err(PipelineError::Print)?;
|
| 77 | print_bytes(&mut transport, &bytes).map_err(PipelineError::Print)
|
| 78 | }
|
| 79 |
|
| 80 | #[cfg(test)]
|
| 81 | mod tests {
|
| 82 | use super::*;
|
| 83 |
|
| 84 | #[test]
|
| 85 | fn detects_missing_parameters() {
|
| 86 | let file = PosFile::new("Hello ${A} ${B}");
|
| 87 | let doc = parse(&file.body).unwrap();
|
| 88 | let mut params = HashMap::new();
|
| 89 | params.insert("A".into(), "1".into());
|
| 90 | assert_eq!(missing_parameters(&doc, ¶ms), vec!["B".to_string()]);
|
| 91 | }
|
| 92 |
|
| 93 | #[test]
|
| 94 | fn encodes_raster_code128_with_substituted_data() {
|
| 95 | let file = PosFile::new("Testing\n@barcode RASTER CODE128 ${Data}\n\nLast line\n");
|
| 96 | let mut params = HashMap::new();
|
| 97 | params.insert("Data".into(), "Testcode".into());
|
| 98 | let bytes = encode_pos_file(&file, None, ¶ms).unwrap();
|
| 99 | assert!(bytes.windows(4).any(|w| w == [0x1D, b'v', 0x30, 0x00]));
|
| 100 | }
|
| 101 |
|
| 102 | #[test]
|
| 103 | fn encodes_when_all_params_present() {
|
| 104 | let file = PosFile::new("Hi ${Name}");
|
| 105 | let mut params = HashMap::new();
|
| 106 | params.insert("Name".into(), "Ada".into());
|
| 107 | let bytes = encode_pos_file(&file, None, ¶ms).unwrap();
|
| 108 | assert!(bytes.windows(2).any(|w| w == b"Hi"));
|
| 109 | }
|
| 110 | }
|