krik 0.1.27

A fast static site generator written in Rust with internationalization, theming, and modern web features
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
use crate::error::{
    GenerationError, GenerationErrorKind, IoError, IoErrorKind, KrikError, KrikResult,
};
use crate::parser::Document;
use crate::site::SiteConfig;
use chrono::Utc;
use rayon::prelude::*;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Mutex;
use tracing::{debug, info, warn};
use which::which;
use crate::I18nManager;

/// PDF generation using pandoc with typst engine
pub struct PdfGenerator {
    pandoc_path: Option<PathBuf>,
    typst_path: Option<PathBuf>,
}

impl PdfGenerator {
    /// Create a new PDF generator, checking for required tools
    pub fn new() -> KrikResult<Self> {
        let pandoc_path = Self::find_executable("pandoc").map_or_else(|| {
            warn!("Pandoc not found in PATH. Install pandoc to enable PDF generation.");
            None
        }, |path| {
            Some(path)
        });

        let typst_path = Self::find_executable("typst").map_or_else(|| {
            warn!("Typst not found in PATH. Install typst to enable PDF generation.");
            None
        }, |path| {
            Some(path)
        });

        debug!("Pandoc path: {}", pandoc_path.clone().unwrap().display());
        debug!("Typst path: {}", typst_path.clone().unwrap().display());

        Ok(Self {
            pandoc_path,
            typst_path,
        })
    }

    /// Check if PDF generation is available (both tools present)
    pub fn is_available() -> bool {
        Self::find_executable("pandoc").is_some() && Self::find_executable("typst").is_some()
    }

    /// Find executable in PATH using the `which` crate (cross-platform)
    fn find_executable(name: &str) -> Option<PathBuf> {
        which(name).ok()
    }

    /// Generate PDF from a markdown file path
    pub fn generate_pdf_from_file(
        &self,
        input_path: &Path,
        output_path: &Path,
        source_root: &Path,
        site_config: &SiteConfig,
        document_language: &str,
    ) -> KrikResult<()> {
        if self.pandoc_path.is_none() {
            warn!("Pandoc not found in PATH. Install pandoc to enable PDF generation.");
            return Ok(());
        }
        // Ensure the output directory exists
        if let Some(parent) = output_path.parent() {
            fs::create_dir_all(parent).map_err(|e| {
                KrikError::Io(Box::new(IoError {
                    kind: IoErrorKind::WriteFailed(e),
                    path: parent.to_path_buf(),
                    context: "Creating PDF output directory".to_string(),
                }))
            })?;
        }

        // Create a temporary filtered markdown file
        let temp_md_file = self.create_filtered_markdown(
            input_path,
            output_path,
            source_root,
            site_config,
            document_language,
        )?;

        // Run pandoc with typst engine on the temporary file
        let mut cmd = Command::new(&self.pandoc_path.clone().unwrap());
        cmd.arg(&temp_md_file)
            .arg("--from=gfm")
            .arg("--pdf-engine=typst")
            .arg("--output")
            .arg(output_path)
            .arg("--standalone")
            .current_dir(source_root);

        // Execute pandoc
        let output = cmd.output().map_err(|e| {
            KrikError::Generation(Box::new(GenerationError {
                kind: GenerationErrorKind::FeedError(format!("Failed to execute pandoc: {e}")),
                context: "Running pandoc to generate PDF".to_string(),
            }))
        })?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(KrikError::Generation(Box::new(GenerationError {
                kind: GenerationErrorKind::FeedError(format!("Pandoc failed: {stderr}")),
                context: "Converting markdown to PDF with pandoc".to_string(),
            })));
        }

        // Clean up temporary markdown file
        let _ = fs::remove_file(&temp_md_file);

        Ok(())
    }

    /// Create a filtered markdown file for PDF generation
    fn create_filtered_markdown(
        &self,
        input_path: &Path,
        output_path: &Path,
        source_root: &Path,
        site_config: &SiteConfig,
        document_language: &str,
    ) -> KrikResult<PathBuf> {
        // Read the original markdown content
        let content = fs::read_to_string(input_path).map_err(|e| {
            KrikError::Io(Box::new(IoError {
                kind: IoErrorKind::ReadFailed(e),
                path: input_path.to_path_buf(),
                context: "Reading markdown file for PDF generation".to_string(),
            }))
        })?;

        // Parse front matter and content
        let (front_matter, markdown_content) = self.parse_front_matter(&content)?;

        // Fix relative image paths by resolving them to absolute paths from source root
        let content_with_fixed_paths =
            self.resolve_relative_image_paths(&markdown_content, input_path, source_root)?;

        // Build the filtered markdown content
        let mut filtered_content = String::new();

        // Add title heading if it exists in front matter and not already in content
        if let Some(title) = &front_matter.title {
            if !content_with_fixed_paths.trim_start().starts_with("# ") {
                filtered_content.push_str(&format!("# {title}\n\n"));
            }
        }

        // Add the main content
        filtered_content.push_str(&content_with_fixed_paths);

        // Add appendix with download information (only if base_url is configured)
        if let Some(base_url) = site_config.get_base_url() {
            let absolute_pdf_url = self.generate_absolute_pdf_url(output_path, &base_url);

            filtered_content.push_str("\n\n---\n\n");

            // Document Information heading
            let doc_info_heading = I18nManager::translate_string("document_information", document_language);
            filtered_content.push_str(&format!("## {doc_info_heading}\n\n"));

            // Download URL line
            let download_text =
                I18nManager::translate_string("document_downloaded_from", document_language);
            filtered_content.push_str(&format!("{download_text} {absolute_pdf_url}\n\n"));

            // Generation timestamp line
            let generated_text = I18nManager::translate_string("generated_at", document_language);
            let timestamp = Utc::now().format("%Y-%m-%d %H:%M:%S UTC");
            filtered_content.push_str(&format!("{generated_text} {timestamp}\n"));
        }

        // Create unique temporary file for concurrent jobs
        static COUNTER: AtomicU64 = AtomicU64::new(0);
        let unique = COUNTER.fetch_add(1, Ordering::Relaxed);
        let safe_stem = input_path
            .file_stem()
            .map(|s| s.to_string_lossy())
            .unwrap_or_default()
            .replace(|c: char| !c.is_ascii_alphanumeric(), "_");
        let temp_file = std::env::temp_dir().join(format!(
            "krik_pdf_{}_{}_{}.md",
            safe_stem,
            std::process::id(),
            unique
        ));

        // Write the filtered content to temporary file
        fs::write(&temp_file, filtered_content).map_err(|e| {
            KrikError::Io(Box::new(IoError {
                kind: IoErrorKind::WriteFailed(e),
                path: temp_file.clone(),
                context: "Writing temporary filtered markdown file".to_string(),
            }))
        })?;

        Ok(temp_file)
    }

    /// Parse front matter from markdown content
    fn parse_front_matter(
        &self,
        content: &str,
    ) -> KrikResult<(crate::parser::FrontMatter, String)> {
        crate::parser::parse_markdown_with_frontmatter(content)
    }

    /// Generate absolute PDF URL for the appendix
    pub fn generate_absolute_pdf_url(&self, output_path: &Path, base_url: &str) -> String {
        let relative_path = self.generate_relative_pdf_path(output_path);
        let base_url_trimmed = base_url.trim_end_matches('/');
        format!("{base_url_trimmed}{relative_path}")
    }

    /// Generate the relative PDF path
    pub fn generate_relative_pdf_path(&self, output_path: &Path) -> String {
        // Extract just the filename and create a relative URL
        if let Some(filename) = output_path.file_name() {
            // Get the directory path relative to _site
            if let Some(parent) = output_path.parent() {
                if let Some(parent_name) = parent.file_name() {
                    // Skip if parent is "_site" (use filename only)
                    if parent_name == "_site" {
                        return format!("/{}", filename.to_string_lossy());
                    }
                    return format!(
                        "/{}/{}",
                        parent_name.to_string_lossy(),
                        filename.to_string_lossy()
                    );
                }
            }
            // Fallback to just filename
            format!("/{}", filename.to_string_lossy())
        } else {
            // Fallback URL
            "/document.pdf".to_string()
        }
    }

    /// Resolve relative image paths in markdown content
    fn resolve_relative_image_paths(
        &self,
        content: &str,
        input_path: &Path,
        source_root: &Path,
    ) -> KrikResult<String> {
        // Use regex to find all markdown image patterns: ![alt](path) and ![alt](path "title")
        use regex::Regex;

        let img_regex =
            Regex::new(r#"!\[([^]]*)]\(([^)]+?)(?:\s+["']([^"']*?)["'])?\)"#).map_err(|e| {
                KrikError::Generation(Box::new(GenerationError {
                    kind: GenerationErrorKind::FeedError(format!(
                        "Failed to compile image regex: {e}"
                    )),
                    context: "Processing markdown image paths".to_string(),
                }))
            })?;

        let mut fixed_content = content.to_string();
        let input_dir = input_path.parent().unwrap_or(Path::new(""));

        // Find all matches and replace them
        let matches: Vec<_> = img_regex.find_iter(content).collect();

        // Process matches in reverse order to avoid offset issues when replacing
        for img_match in matches.iter().rev() {
            let full_match = img_match.as_str();

            // Parse the match to extract components
            if let Some(caps) = img_regex.captures(full_match) {
                let alt_text = caps.get(1).map_or("", |m| m.as_str());
                let original_path = caps.get(2).map_or("", |m| m.as_str());
                let title = caps.get(3).map(|m| m.as_str());

                // Only process relative paths (not URLs or absolute paths)
                if !original_path.starts_with("http")
                    && !original_path.starts_with("/")
                    && !original_path.is_empty()
                {
                    // Resolve the relative path from the markdown file's directory
                    let resolved_path =
                        self.resolve_relative_path(original_path, input_dir, source_root);

                    // Create the replacement markdown image syntax
                    let replacement = if let Some(title_text) = title {
                        format!("![{alt_text}]({resolved_path} \"{title_text}\")")
                    } else {
                        format!("![{alt_text}]({resolved_path})")
                    };

                    // Replace in the content
                    let start = img_match.start();
                    let end = img_match.end();
                    fixed_content.replace_range(start..end, &replacement);
                }
            }
        }

        Ok(fixed_content)
    }

    /// Resolve a relative path from a markdown file to an absolute path from source root
    pub fn resolve_relative_path(
        &self,
        relative_path: &str,
        input_dir: &Path,
        source_root: &Path,
    ) -> String {
        // First canonicalize both paths to handle any .. or . components
        let canonical_input_dir =
            fs::canonicalize(input_dir).unwrap_or_else(|_| input_dir.to_path_buf());
        let canonical_source_root =
            fs::canonicalize(source_root).unwrap_or_else(|_| source_root.to_path_buf());

        // Try to make input_dir relative to source_root
        let input_relative_to_source =
            match canonical_input_dir.strip_prefix(&canonical_source_root) {
                Ok(relative) => relative.to_path_buf(),
                Err(_) => {
                    // If outside source root, normalize the path but keep it absolute
                    let joined = canonical_input_dir.join(relative_path);
                    return self
                        .normalize_path(&joined)
                        .to_string_lossy()
                        .replace('\\', "/");
                }
            };

        // For paths within source root, resolve relative to source root
        let resolved_path = input_relative_to_source.join(relative_path);
        let normalized = self.normalize_path(&resolved_path);

        // Convert back to string with forward slashes for consistency
        normalized.to_string_lossy().replace('\\', "/")
    }

    /// Normalize a path by resolving . and .. components
    pub fn normalize_path(&self, path: &Path) -> PathBuf {
        let mut result = PathBuf::new();

        for component in path.components() {
            match component {
                std::path::Component::Normal(name) => result.push(name),
                std::path::Component::ParentDir => {
                    result.pop();
                }
                std::path::Component::CurDir => {
                    // Skip current directory references
                }
                _ => result.push(component),
            }
        }

        result
    }

    /// Generate PDFs for documents that have pdf: true in their front matter
    pub fn generate_pdfs(
        &self,
        documents: &[Document],
        source_dir: &Path,
        output_dir: &Path,
        site_config: &SiteConfig,
    ) -> KrikResult<Vec<PathBuf>> {
        // Filter documents that have pdf: true
        let pdf_documents: Vec<&Document> = documents
            .iter()
            .filter(|doc| doc.front_matter.pdf.unwrap_or(false))
            .collect();

        if pdf_documents.is_empty() {
            info!("No documents marked for PDF generation (pdf: true)");
            return Ok(Vec::new());
        }

        info!(
            "Generating PDFs for {} documents marked with pdf: true",
            pdf_documents.len()
        );

        // Determine project root by canonicalizing the source directory path
        let canonical_source_dir = fs::canonicalize(source_dir).map_err(|e| {
            KrikError::Io(Box::new(IoError {
                kind: IoErrorKind::ReadFailed(e),
                path: source_dir.to_path_buf(),
                context: "Canonicalizing source directory path".to_string(),
            }))
        })?;

        let project_root = canonical_source_dir
            .parent()
            .unwrap_or(&canonical_source_dir)
            .to_path_buf();

        let results: Mutex<Vec<PathBuf>> = Mutex::new(Vec::with_capacity(pdf_documents.len()));

        pdf_documents.par_iter().for_each(|document| {
            let input_path = source_dir.join(&document.file_path);
            let output_path = self.determine_pdf_output_path(document, output_dir);

            match self.generate_pdf_from_file(
                &input_path,
                &output_path,
                &project_root,
                site_config,
                &document.language,
            ) {
                Ok(()) => {
                    info!("Generated PDF: {}", output_path.display());
                    if let Ok(mut guard) = results.lock() {
                        guard.push(output_path);
                    }
                }
                Err(e) => {
                    warn!(
                        "Warning: Failed to generate PDF for {}: {}",
                        document.file_path, e
                    );
                }
            }
        });

        let mut generated = results.into_inner().unwrap_or_default();
        generated.sort();
        Ok(generated)
    }

    /// Determine the output path for a PDF file (same directory as HTML)
    fn determine_pdf_output_path(&self, document: &Document, output_dir: &Path) -> PathBuf {
        let mut path = PathBuf::from(&document.file_path);
        path.set_extension("pdf");
        output_dir.join(path)
    }

    /// Get version information for diagnostics
    pub fn version_info(&self) -> KrikResult<(String, String)> {
        let pandoc_version = self.get_tool_version(&self.pandoc_path.clone().unwrap(), &["--version"])?;
        let typst_version = self.get_tool_version(&self.typst_path.clone().unwrap(), &["--version"])?;

        Ok((pandoc_version, typst_version))
    }

    fn get_tool_version(&self, tool_path: &Path, args: &[&str]) -> KrikResult<String> {
        let output = Command::new(tool_path).args(args).output().map_err(|e| {
            KrikError::Generation(Box::new(GenerationError {
                kind: GenerationErrorKind::FeedError(format!(
                    "Failed to get version for {}: {}",
                    tool_path.display(),
                    e
                )),
                context: "Getting tool version information".to_string(),
            }))
        })?;

        if output.status.success() {
            let version_output = String::from_utf8_lossy(&output.stdout);
            let first_line = version_output.lines().next().unwrap_or("Unknown").trim();
            Ok(first_line.to_string())
        } else {
            Err(KrikError::Generation(Box::new(GenerationError {
                kind: GenerationErrorKind::FeedError(format!(
                    "Failed to get version for {}",
                    tool_path.display()
                )),
                context: "Getting tool version information".to_string(),
            })))
        }
    }
}