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
//! Test manifest utilities for unified test reporting.
//!
//! This module provides utilities for tests to write their results to a manifest
//! file that can be consumed by the report generator.

#![allow(missing_docs)]
#![allow(dead_code)]
#![allow(clippy::missing_docs_in_private_items)]

use serde::{Deserialize, Serialize};
use std::fs::{self, File};
use std::io::BufReader;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::Instant;

/// Test source identifier
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum TestSource {
    Cli,
    Core,
    Node,
    Python,
}

/// Test category for grouping
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum TestCategory {
    Conversion,
    Orientation,
    Fonts,
    Images,
    Forms,
    Batch,
    Watermark,
    Bookmarks,
    Annotations,
    Url,
    Metadata,
}

/// Test result status
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum TestStatus {
    Pass,
    Fail,
    Skip,
    Error,
}

/// Input information for a test
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TestInput {
    #[serde(rename = "type")]
    pub input_type: Option<String>,
    pub path: Option<String>,
}

/// Output information for a test
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TestOutput {
    pub path: Option<String>,
    pub size_bytes: Option<u64>,
}

/// Expected properties of the PDF output
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ExpectedProperties {
    pub orientation: Option<String>,
    pub page_count: Option<u32>,
    pub page_size: Option<String>,
}

/// Actual measured properties of the PDF output
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ActualProperties {
    pub orientation: Option<String>,
    pub page_count: Option<u32>,
    pub width_pt: Option<f64>,
    pub height_pt: Option<f64>,
}

/// A single test result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestResult {
    pub name: String,
    pub category: TestCategory,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input: Option<TestInput>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output: Option<TestOutput>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expected: Option<ExpectedProperties>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub actual: Option<ActualProperties>,
    pub status: TestStatus,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub duration_ms: Option<f64>,
}

/// The complete test manifest
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestManifest {
    pub source: TestSource,
    pub timestamp: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    pub tests: Vec<TestResult>,
}

impl TestManifest {
    /// Create a new empty manifest
    pub fn new(source: TestSource) -> Self {
        Self {
            source,
            timestamp: chrono_now(),
            version: option_env!("CARGO_PKG_VERSION").map(|s| s.to_string()),
            tests: Vec::new(),
        }
    }

    /// Load manifest from file, or create new if doesn't exist
    pub fn load_or_create(path: &Path, source: TestSource) -> Self {
        if path.exists() {
            match File::open(path) {
                Ok(file) => {
                    let reader = BufReader::new(file);
                    match serde_json::from_reader(reader) {
                        Ok(manifest) => return manifest,
                        Err(e) => eprintln!("Warning: Failed to parse manifest: {}", e),
                    }
                }
                Err(e) => eprintln!("Warning: Failed to open manifest: {}", e),
            }
        }
        Self::new(source)
    }

    /// Add a test result
    pub fn add_result(&mut self, result: TestResult) {
        // Remove existing result with same name if present
        self.tests.retain(|t| t.name != result.name);
        self.tests.push(result);
    }

    /// Write manifest to file
    pub fn write(&self, path: &Path) -> std::io::Result<()> {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        let file = File::create(path)?;
        serde_json::to_writer_pretty(file, self)?;
        Ok(())
    }
}

/// Builder for creating test results
pub struct TestResultBuilder {
    name: String,
    category: TestCategory,
    description: Option<String>,
    input: Option<TestInput>,
    output: Option<TestOutput>,
    expected: Option<ExpectedProperties>,
    actual: Option<ActualProperties>,
    status: TestStatus,
    error: Option<String>,
    start_time: Option<Instant>,
    duration_ms: Option<f64>,
}

impl TestResultBuilder {
    /// Create a new test result builder
    pub fn new(name: &str, category: TestCategory) -> Self {
        Self {
            name: name.to_string(),
            category,
            description: None,
            input: None,
            output: None,
            expected: None,
            actual: None,
            status: TestStatus::Pass,
            error: None,
            start_time: None,
            duration_ms: None,
        }
    }

    /// Set the test description
    pub fn description(mut self, desc: &str) -> Self {
        self.description = Some(desc.to_string());
        self
    }

    /// Set input as HTML file
    pub fn input_html_file(mut self, path: &str) -> Self {
        self.input = Some(TestInput {
            input_type: Some("html_file".to_string()),
            path: Some(path.to_string()),
        });
        self
    }

    /// Set input as URL
    pub fn input_url(mut self, url: &str) -> Self {
        self.input = Some(TestInput {
            input_type: Some("url".to_string()),
            path: Some(url.to_string()),
        });
        self
    }

    /// Set input as PDF file (for watermark/bookmark tests)
    pub fn input_pdf_file(mut self, path: &str) -> Self {
        self.input = Some(TestInput {
            input_type: Some("pdf_file".to_string()),
            path: Some(path.to_string()),
        });
        self
    }

    /// Set output path
    pub fn output_path(mut self, path: &str) -> Self {
        let size = fs::metadata(path).map(|m| m.len()).ok();
        self.output = Some(TestOutput {
            path: Some(path.to_string()),
            size_bytes: size,
        });
        self
    }

    /// Set expected orientation
    pub fn expect_orientation(mut self, orientation: &str) -> Self {
        let mut expected = self.expected.unwrap_or_default();
        expected.orientation = Some(orientation.to_string());
        self.expected = Some(expected);
        self
    }

    /// Set expected page count
    pub fn expect_page_count(mut self, count: u32) -> Self {
        let mut expected = self.expected.unwrap_or_default();
        expected.page_count = Some(count);
        self.expected = Some(expected);
        self
    }

    /// Set actual properties from PDF analysis
    pub fn actual_properties(
        mut self,
        orientation: &str,
        page_count: u32,
        width: f64,
        height: f64,
    ) -> Self {
        self.actual = Some(ActualProperties {
            orientation: Some(orientation.to_string()),
            page_count: Some(page_count),
            width_pt: Some(width),
            height_pt: Some(height),
        });
        self
    }

    /// Mark test as passed
    pub fn pass(mut self) -> Self {
        self.status = TestStatus::Pass;
        self.error = None;
        self
    }

    /// Mark test as failed with error message
    pub fn fail(mut self, error: &str) -> Self {
        self.status = TestStatus::Fail;
        self.error = Some(error.to_string());
        self
    }

    /// Mark test as skipped
    pub fn skip(mut self, reason: &str) -> Self {
        self.status = TestStatus::Skip;
        self.error = Some(reason.to_string());
        self
    }

    /// Start timing
    pub fn start_timer(mut self) -> Self {
        self.start_time = Some(Instant::now());
        self
    }

    /// Stop timing and record duration
    pub fn stop_timer(mut self) -> Self {
        if let Some(start) = self.start_time {
            self.duration_ms = Some(start.elapsed().as_secs_f64() * 1000.0);
        }
        self
    }

    /// Build the test result
    pub fn build(self) -> TestResult {
        TestResult {
            name: self.name,
            category: self.category,
            description: self.description,
            input: self.input,
            output: self.output,
            expected: self.expected,
            actual: self.actual,
            status: self.status,
            error: self.error,
            duration_ms: self.duration_ms,
        }
    }
}

/// Global manifest writer for thread-safe test result collection
static MANIFEST: Mutex<Option<TestManifest>> = Mutex::new(None);
static MANIFEST_PATH: Mutex<Option<PathBuf>> = Mutex::new(None);

/// Initialize the global manifest for a test run
pub fn init_manifest(output_dir: &Path, source: TestSource) {
    let manifest_path = output_dir.join("manifest.json");
    let manifest = TestManifest::load_or_create(&manifest_path, source);

    *MANIFEST.lock().unwrap() = Some(manifest);
    *MANIFEST_PATH.lock().unwrap() = Some(manifest_path);
}

/// Record a test result to the global manifest
pub fn record_test(result: TestResult) {
    if let Some(ref mut manifest) = *MANIFEST.lock().unwrap() {
        manifest.add_result(result);
    }
}

/// Save the global manifest to disk
pub fn save_manifest() {
    let manifest = MANIFEST.lock().unwrap();
    let path = MANIFEST_PATH.lock().unwrap();

    if let (Some(m), Some(p)) = (manifest.as_ref(), path.as_ref()) {
        if let Err(e) = m.write(p) {
            eprintln!("Warning: Failed to write manifest: {}", e);
        }
    }
}

/// Get current timestamp as ISO 8601 string
fn chrono_now() -> String {
    use std::time::SystemTime;
    let now = SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs();

    let days_since_epoch = now / 86400;
    let seconds_today = now % 86400;
    let hours = seconds_today / 3600;
    let minutes = (seconds_today % 3600) / 60;
    let seconds = seconds_today % 60;

    let mut year = 1970i64;
    let mut remaining_days = days_since_epoch as i64;

    loop {
        let days_in_year = if is_leap_year(year) { 366 } else { 365 };
        if remaining_days < days_in_year {
            break;
        }
        remaining_days -= days_in_year;
        year += 1;
    }

    let months = [
        31,
        28 + if is_leap_year(year) { 1 } else { 0 },
        31,
        30,
        31,
        30,
        31,
        31,
        30,
        31,
        30,
        31,
    ];
    let mut month = 1;
    for days_in_month in months {
        if remaining_days < days_in_month {
            break;
        }
        remaining_days -= days_in_month;
        month += 1;
    }

    let day = remaining_days + 1;

    format!(
        "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
        year, month, day, hours, minutes, seconds
    )
}

fn is_leap_year(year: i64) -> bool {
    (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
}

/// Extract PDF metadata from a file for actual properties
pub fn extract_pdf_metadata(pdf_path: &Path) -> Option<ActualProperties> {
    let content = fs::read(pdf_path).ok()?;
    let content_str = String::from_utf8_lossy(&content);

    // Count pages
    let page_count = content_str.matches("/Type /Page").count().max(1) as u32;

    // Find MediaBox
    let (width, height) = if let Some(pos) = content_str.find("/MediaBox") {
        parse_media_box(&content_str[pos..]).unwrap_or((612.0, 792.0))
    } else {
        (612.0, 792.0)
    };

    let orientation = if width > height {
        "landscape"
    } else {
        "portrait"
    };

    Some(ActualProperties {
        orientation: Some(orientation.to_string()),
        page_count: Some(page_count),
        width_pt: Some(width),
        height_pt: Some(height),
    })
}

fn parse_media_box(content: &str) -> Option<(f64, f64)> {
    let start = content.find('[')? + 1;
    let end = content.find(']')?;
    let box_content = &content[start..end];

    let parts: Vec<f64> = box_content
        .split_whitespace()
        .filter_map(|s| s.parse().ok())
        .collect();

    if parts.len() >= 4 {
        Some((parts[2], parts[3]))
    } else {
        None
    }
}