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