printwell-cli 0.1.11

Command-line tool for HTML to PDF conversion
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
//! Parsing utilities for CLI arguments.
//!
//! This module provides reusable parsing functions for common CLI argument patterns.

use anyhow::{Context, Result};

/// Parse page size string to dimensions in mm.
pub fn parse_page_size(size: &str) -> Result<(f64, f64)> {
    match size.to_uppercase().as_str() {
        "A3" => Ok((297.0, 420.0)),
        "A4" => Ok((210.0, 297.0)),
        "A5" => Ok((148.0, 210.0)),
        "LETTER" => Ok((215.9, 279.4)),
        "LEGAL" => Ok((215.9, 355.6)),
        "TABLOID" => Ok((279.4, 431.8)),
        _ => anyhow::bail!("Unknown page size: {size}. Use A3, A4, A5, Letter, Legal, or Tabloid"),
    }
}

/// Parse length string (e.g., "10mm", "1in") to mm.
pub fn parse_length_mm(s: &str) -> Result<f64> {
    let s = s.trim();
    if let Some(v) = s.strip_suffix("mm") {
        v.trim().parse().context("Invalid mm value")
    } else if let Some(v) = s.strip_suffix("cm") {
        let v: f64 = v.trim().parse().context("Invalid cm value")?;
        Ok(v * 10.0)
    } else if let Some(v) = s.strip_suffix("in") {
        let v: f64 = v.trim().parse().context("Invalid in value")?;
        Ok(v * 25.4)
    } else if let Some(v) = s.strip_suffix("pt") {
        let v: f64 = v.trim().parse().context("Invalid pt value")?;
        Ok(v * 25.4 / 72.0)
    } else if let Some(v) = s.strip_suffix("px") {
        let v: f64 = v.trim().parse().context("Invalid px value")?;
        Ok(v * 25.4 / 96.0)
    } else {
        // Default to mm
        s.parse().context("Invalid length value")
    }
}

/// Parse margin string (single value or "top,right,bottom,left").
pub fn parse_margins(s: &str) -> Result<(f64, f64, f64, f64)> {
    let parts: Vec<&str> = s.split(',').collect();
    match parts.len() {
        1 => {
            let m = parse_length_mm(parts[0])?;
            Ok((m, m, m, m))
        }
        2 => {
            let v = parse_length_mm(parts[0])?;
            let h = parse_length_mm(parts[1])?;
            Ok((v, h, v, h))
        }
        4 => {
            let top = parse_length_mm(parts[0])?;
            let right = parse_length_mm(parts[1])?;
            let bottom = parse_length_mm(parts[2])?;
            let left = parse_length_mm(parts[3])?;
            Ok((top, right, bottom, left))
        }
        _ => anyhow::bail!(
            "Invalid margin format. Use 'value', 'vertical,horizontal', or 'top,right,bottom,left'"
        ),
    }
}

/// Parse timeout string (e.g., "30s", "1m").
#[allow(dead_code)] // May be used by future features
pub fn parse_timeout_ms(s: &str) -> Result<u32> {
    let s = s.trim();
    if let Some(v) = s.strip_suffix("ms") {
        v.trim().parse().context("Invalid ms value")
    } else if let Some(v) = s.strip_suffix('s') {
        let v: u32 = v.trim().parse().context("Invalid s value")?;
        Ok(v * 1000)
    } else if let Some(v) = s.strip_suffix('m') {
        let v: u32 = v.trim().parse().context("Invalid m value")?;
        Ok(v * 60 * 1000)
    } else {
        s.parse().context("Invalid timeout value")
    }
}

/// Parse coordinate string into a vector of f64 values.
#[allow(dead_code)]
pub fn parse_coords(spec: &str, count: usize) -> Result<Vec<f64>> {
    let coords: Vec<f64> = spec
        .split(',')
        .map(|s| s.trim().parse::<f64>())
        .collect::<std::result::Result<_, _>>()
        .context("Invalid coordinates")?;
    if coords.len() != count {
        anyhow::bail!("Expected {count} coordinate values, got {}", coords.len());
    }
    Ok(coords)
}

/// Parse "page:coords" string.
#[allow(dead_code)]
pub fn parse_page_coords(
    spec: &str,
    coord_count: usize,
    format_hint: &str,
) -> Result<(u32, Vec<f64>)> {
    let parts: Vec<&str> = spec.split(':').collect();
    if parts.len() != 2 {
        anyhow::bail!("Invalid format. Use: {format_hint}");
    }
    let page: u32 = parts[0].parse().context("Invalid page number")?;
    let coords = parse_coords(parts[1], coord_count)?;
    Ok((page, coords))
}

// ============================================================================
// Page Selection Parsing
// ============================================================================

/// Page selection for operations that can target specific pages.
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(dead_code)] // Used by feature-gated modules (watermark)
pub enum PageSelection {
    /// All pages
    All,
    /// Specific page numbers (1-indexed)
    Pages(Vec<u32>),
    /// Page range (inclusive, 1-indexed)
    Range(u32, u32),
    /// Odd pages only
    Odd,
    /// Even pages only
    Even,
    /// First page only
    First,
    /// Last page only
    Last,
}

/// Parse a page selection string.
///
/// Supports:
/// - `None` or empty -> All pages
/// - `"odd"` -> Odd pages only
/// - `"even"` -> Even pages only
/// - `"first"` -> First page only
/// - `"last"` -> Last page only
/// - `"1-5"` -> Pages 1 through 5 (inclusive)
/// - `"1,3,5"` -> Pages 1, 3, and 5
#[allow(dead_code)] // Used by feature-gated modules (watermark)
pub fn parse_page_selection(s: Option<&str>) -> Result<PageSelection> {
    match s {
        None | Some("") => Ok(PageSelection::All),
        Some("odd") => Ok(PageSelection::Odd),
        Some("even") => Ok(PageSelection::Even),
        Some("first") => Ok(PageSelection::First),
        Some("last") => Ok(PageSelection::Last),
        Some(pages_str) => {
            if let Some((start, end)) = pages_str.split_once('-') {
                let start: u32 = start
                    .trim()
                    .parse()
                    .context("Invalid start page in range")?;
                let end: u32 = end.trim().parse().context("Invalid end page in range")?;
                if start > end {
                    anyhow::bail!("Start page ({start}) must be <= end page ({end})");
                }
                Ok(PageSelection::Range(start, end))
            } else {
                let pages: Vec<u32> = pages_str
                    .split(',')
                    .map(|s| s.trim().parse::<u32>())
                    .collect::<std::result::Result<_, _>>()
                    .context("Invalid page numbers")?;
                if pages.is_empty() {
                    anyhow::bail!("No page numbers specified");
                }
                Ok(PageSelection::Pages(pages))
            }
        }
    }
}

// ============================================================================
// Color Parsing
// ============================================================================

/// Parse a color string (named color or hex).
///
/// Named colors: red, green, blue, black, white, gray/grey, yellow, cyan, magenta
/// Hex format: #RRGGBB or RRGGBB
#[allow(dead_code)] // Used by feature-gated modules (watermark, annotate)
pub fn parse_color_hex(s: &str) -> Result<(u8, u8, u8)> {
    match s.to_lowercase().as_str() {
        "red" => Ok((255, 0, 0)),
        "green" => Ok((0, 255, 0)),
        "blue" => Ok((0, 0, 255)),
        "black" => Ok((0, 0, 0)),
        "white" => Ok((255, 255, 255)),
        "gray" | "grey" => Ok((128, 128, 128)),
        "yellow" => Ok((255, 255, 0)),
        "cyan" => Ok((0, 255, 255)),
        "magenta" => Ok((255, 0, 255)),
        "orange" => Ok((255, 165, 0)),
        "purple" => Ok((128, 0, 128)),
        "pink" => Ok((255, 192, 203)),
        hex => {
            let hex = hex.strip_prefix('#').unwrap_or(hex);
            if hex.len() != 6 {
                anyhow::bail!("Invalid hex color format. Use #RRGGBB or RRGGBB");
            }
            let r =
                u8::from_str_radix(&hex[0..2], 16).context("Invalid red component in hex color")?;
            let g = u8::from_str_radix(&hex[2..4], 16)
                .context("Invalid green component in hex color")?;
            let b = u8::from_str_radix(&hex[4..6], 16)
                .context("Invalid blue component in hex color")?;
            Ok((r, g, b))
        }
    }
}

// ============================================================================
// Colon-Separated Spec Parsing
// ============================================================================

/// Parse a colon-separated specification string.
///
/// Returns a vector of string parts split by ':'.
/// Useful for parsing specs like "page:x:y:width:height" or "`title:page:y_position`".
pub fn parse_colon_spec<'a>(
    spec: &'a str,
    min_parts: usize,
    format_hint: &str,
) -> Result<Vec<&'a str>> {
    let parts: Vec<&str> = spec.split(':').collect();
    if parts.len() < min_parts {
        anyhow::bail!("Invalid format. Expected: {format_hint}");
    }
    Ok(parts)
}

/// Parse a colon-separated spec with a page number as the first element.
///
/// Returns (`page_number`, `remaining_parts`).
#[allow(dead_code)]
pub fn parse_page_spec<'a>(
    spec: &'a str,
    min_extra_parts: usize,
    format_hint: &str,
) -> Result<(u32, Vec<&'a str>)> {
    let parts = parse_colon_spec(spec, min_extra_parts + 1, format_hint)?;
    let page: u32 = parts[0]
        .parse()
        .with_context(|| format!("Invalid page number: {}", parts[0]))?;
    Ok((page, parts[1..].to_vec()))
}

/// Parse a rectangle specification from colon-separated parts.
///
/// Expects 4 values: x, y, width, height.
#[allow(dead_code)] // Used by feature-gated modules (annotate)
pub fn parse_rect_from_parts(parts: &[&str], start_index: usize) -> Result<(f32, f32, f32, f32)> {
    if parts.len() < start_index + 4 {
        anyhow::bail!("Not enough values for rectangle (need x, y, width, height)");
    }
    let pos_x: f32 = parts[start_index]
        .parse()
        .with_context(|| format!("Invalid x coordinate: {}", parts[start_index]))?;
    let pos_y: f32 = parts[start_index + 1]
        .parse()
        .with_context(|| format!("Invalid y coordinate: {}", parts[start_index + 1]))?;
    let width: f32 = parts[start_index + 2]
        .parse()
        .with_context(|| format!("Invalid width: {}", parts[start_index + 2]))?;
    let height: f32 = parts[start_index + 3]
        .parse()
        .with_context(|| format!("Invalid height: {}", parts[start_index + 3]))?;
    Ok((pos_x, pos_y, width, height))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn approx_eq(a: f64, b: f64) -> bool {
        (a - b).abs() < 0.001
    }

    fn approx_eq_tuple(a: (f64, f64), b: (f64, f64)) -> bool {
        approx_eq(a.0, b.0) && approx_eq(a.1, b.1)
    }

    fn approx_eq_quad(a: (f64, f64, f64, f64), b: (f64, f64, f64, f64)) -> bool {
        approx_eq(a.0, b.0) && approx_eq(a.1, b.1) && approx_eq(a.2, b.2) && approx_eq(a.3, b.3)
    }

    fn approx_eq_vec(a: &[f64], b: &[f64]) -> bool {
        a.len() == b.len() && a.iter().zip(b.iter()).all(|(x, y)| approx_eq(*x, *y))
    }

    #[test]
    fn test_parse_page_size_valid() {
        assert!(approx_eq_tuple(
            parse_page_size("A4").unwrap(),
            (210.0, 297.0)
        ));
        assert!(approx_eq_tuple(
            parse_page_size("a4").unwrap(),
            (210.0, 297.0)
        ));
        assert!(approx_eq_tuple(
            parse_page_size("A3").unwrap(),
            (297.0, 420.0)
        ));
        assert!(approx_eq_tuple(
            parse_page_size("A5").unwrap(),
            (148.0, 210.0)
        ));
        assert!(approx_eq_tuple(
            parse_page_size("Letter").unwrap(),
            (215.9, 279.4)
        ));
        assert!(approx_eq_tuple(
            parse_page_size("LEGAL").unwrap(),
            (215.9, 355.6)
        ));
        assert!(approx_eq_tuple(
            parse_page_size("tabloid").unwrap(),
            (279.4, 431.8)
        ));
    }

    #[test]
    fn test_parse_page_size_invalid() {
        assert!(parse_page_size("A6").is_err());
        assert!(parse_page_size("").is_err());
        assert!(parse_page_size("unknown").is_err());
    }

    #[test]
    fn test_parse_length_mm_valid() {
        assert!(approx_eq(parse_length_mm("10mm").unwrap(), 10.0));
        assert!(approx_eq(parse_length_mm("10").unwrap(), 10.0));
        assert!(approx_eq(parse_length_mm("1cm").unwrap(), 10.0));
        assert!(approx_eq(parse_length_mm("1in").unwrap(), 25.4));
        assert!((parse_length_mm("72pt").unwrap() - 25.4).abs() < 0.01);
        assert!((parse_length_mm("96px").unwrap() - 25.4).abs() < 0.01);
    }

    #[test]
    fn test_parse_length_mm_invalid() {
        assert!(parse_length_mm("abc").is_err());
        assert!(parse_length_mm("mm").is_err());
        assert!(parse_length_mm("10xyz").is_err());
    }

    #[test]
    fn test_parse_margins_single_value() {
        assert!(approx_eq_quad(
            parse_margins("10mm").unwrap(),
            (10.0, 10.0, 10.0, 10.0)
        ));
    }

    #[test]
    fn test_parse_margins_two_values() {
        assert!(approx_eq_quad(
            parse_margins("10mm,20mm").unwrap(),
            (10.0, 20.0, 10.0, 20.0)
        ));
    }

    #[test]
    fn test_parse_margins_four_values() {
        assert!(approx_eq_quad(
            parse_margins("10mm,20mm,30mm,40mm").unwrap(),
            (10.0, 20.0, 30.0, 40.0)
        ));
    }

    #[test]
    fn test_parse_margins_invalid() {
        assert!(parse_margins("10mm,20mm,30mm").is_err()); // 3 values not allowed
        assert!(parse_margins("10mm,20mm,30mm,40mm,50mm").is_err()); // 5 values not allowed
    }

    #[test]
    fn test_parse_timeout_ms_valid() {
        assert_eq!(parse_timeout_ms("1000ms").unwrap(), 1000);
        assert_eq!(parse_timeout_ms("30s").unwrap(), 30000);
        assert_eq!(parse_timeout_ms("1m").unwrap(), 60000);
        assert_eq!(parse_timeout_ms("5000").unwrap(), 5000);
    }

    #[test]
    fn test_parse_timeout_ms_invalid() {
        assert!(parse_timeout_ms("abc").is_err());
        assert!(parse_timeout_ms("10h").is_err()); // hours not supported
    }

    #[test]
    fn test_parse_coords_valid() {
        assert!(approx_eq_vec(
            &parse_coords("10,20,30,40", 4).unwrap(),
            &[10.0, 20.0, 30.0, 40.0]
        ));
        assert!(approx_eq_vec(
            &parse_coords("1.5,2.5", 2).unwrap(),
            &[1.5, 2.5]
        ));
    }

    #[test]
    fn test_parse_coords_wrong_count() {
        assert!(parse_coords("10,20", 4).is_err());
        assert!(parse_coords("10,20,30,40,50", 4).is_err());
    }

    #[test]
    fn test_parse_coords_invalid_number() {
        assert!(parse_coords("10,abc,30,40", 4).is_err());
    }

    #[test]
    fn test_parse_page_coords_valid() {
        let (page, coords) = parse_page_coords("1:100,200,50,25", 4, "page:x,y,w,h").unwrap();
        assert_eq!(page, 1);
        assert_eq!(coords, vec![100.0, 200.0, 50.0, 25.0]);
    }

    #[test]
    fn test_parse_page_coords_invalid_format() {
        assert!(parse_page_coords("1", 4, "page:x,y,w,h").is_err());
        assert!(parse_page_coords("1:2:3", 4, "page:x,y,w,h").is_err());
    }

    #[test]
    fn test_parse_page_coords_invalid_page() {
        assert!(parse_page_coords("abc:100,200,50,25", 4, "page:x,y,w,h").is_err());
    }

    #[test]
    fn test_parse_page_selection_all() {
        assert_eq!(parse_page_selection(None).unwrap(), PageSelection::All);
        assert_eq!(parse_page_selection(Some("")).unwrap(), PageSelection::All);
    }

    #[test]
    fn test_parse_page_selection_keywords() {
        assert_eq!(
            parse_page_selection(Some("odd")).unwrap(),
            PageSelection::Odd
        );
        assert_eq!(
            parse_page_selection(Some("even")).unwrap(),
            PageSelection::Even
        );
        assert_eq!(
            parse_page_selection(Some("first")).unwrap(),
            PageSelection::First
        );
        assert_eq!(
            parse_page_selection(Some("last")).unwrap(),
            PageSelection::Last
        );
    }

    #[test]
    fn test_parse_page_selection_range() {
        assert_eq!(
            parse_page_selection(Some("1-5")).unwrap(),
            PageSelection::Range(1, 5)
        );
        assert_eq!(
            parse_page_selection(Some("10-20")).unwrap(),
            PageSelection::Range(10, 20)
        );
    }

    #[test]
    fn test_parse_page_selection_list() {
        assert_eq!(
            parse_page_selection(Some("1,3,5")).unwrap(),
            PageSelection::Pages(vec![1, 3, 5])
        );
        assert_eq!(
            parse_page_selection(Some("2, 4, 6")).unwrap(),
            PageSelection::Pages(vec![2, 4, 6])
        );
    }

    #[test]
    fn test_parse_page_selection_invalid() {
        assert!(parse_page_selection(Some("5-1")).is_err()); // reverse range
        assert!(parse_page_selection(Some("abc")).is_err());
    }

    #[test]
    fn test_parse_color_hex_named() {
        assert_eq!(parse_color_hex("red").unwrap(), (255, 0, 0));
        assert_eq!(parse_color_hex("green").unwrap(), (0, 255, 0));
        assert_eq!(parse_color_hex("blue").unwrap(), (0, 0, 255));
        assert_eq!(parse_color_hex("black").unwrap(), (0, 0, 0));
        assert_eq!(parse_color_hex("white").unwrap(), (255, 255, 255));
        assert_eq!(parse_color_hex("gray").unwrap(), (128, 128, 128));
        assert_eq!(parse_color_hex("grey").unwrap(), (128, 128, 128));
        assert_eq!(parse_color_hex("yellow").unwrap(), (255, 255, 0));
    }

    #[test]
    fn test_parse_color_hex_hex() {
        assert_eq!(parse_color_hex("#FF0000").unwrap(), (255, 0, 0));
        assert_eq!(parse_color_hex("00FF00").unwrap(), (0, 255, 0));
        assert_eq!(parse_color_hex("#0000ff").unwrap(), (0, 0, 255));
    }

    #[test]
    fn test_parse_color_hex_invalid() {
        assert!(parse_color_hex("#FFF").is_err()); // too short
        assert!(parse_color_hex("#GGGGGG").is_err()); // invalid hex
        assert!(parse_color_hex("notacolor").is_err());
    }

    #[test]
    fn test_parse_colon_spec_valid() {
        let parts = parse_colon_spec("a:b:c", 3, "x:y:z").unwrap();
        assert_eq!(parts, vec!["a", "b", "c"]);
    }

    #[test]
    fn test_parse_colon_spec_too_few() {
        assert!(parse_colon_spec("a:b", 3, "x:y:z").is_err());
    }

    #[test]
    fn test_parse_page_spec_valid() {
        let (page, parts) = parse_page_spec("5:a:b:c", 3, "page:x:y:z").unwrap();
        assert_eq!(page, 5);
        assert_eq!(parts, vec!["a", "b", "c"]);
    }

    #[test]
    fn test_parse_rect_from_parts_valid() {
        let parts = vec!["1", "100", "200", "50", "25"];
        let (x, y, w, h) = parse_rect_from_parts(&parts, 1).unwrap();
        assert!(approx_eq(f64::from(x), 100.0));
        assert!(approx_eq(f64::from(y), 200.0));
        assert!(approx_eq(f64::from(w), 50.0));
        assert!(approx_eq(f64::from(h), 25.0));
    }

    #[test]
    fn test_parse_rect_from_parts_invalid() {
        let parts = vec!["1", "100", "200"];
        assert!(parse_rect_from_parts(&parts, 1).is_err());
    }
}