zorto-core 0.13.2

Core library for zorto — the AI-native static site generator (SSG) with executable code blocks
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
use std::collections::HashMap;

use crate::config::Config;
use crate::content::{self, Page, Section};

/// A taxonomy term for template rendering
#[derive(Debug, Clone, serde::Serialize)]
pub struct TaxonomyTerm {
    pub name: String,
    pub slug: String,
    pub permalink: String,
    pub pages: Vec<Page>,
}

/// Paginator for template rendering
#[derive(Debug, Clone, serde::Serialize)]
pub struct Paginator {
    pub pages: Vec<Page>,
    pub current_index: usize,
    pub number_pagers: usize,
    pub previous: Option<String>,
    pub next: Option<String>,
    pub first: String,
    pub last: String,
}

/// Set up Tera engine with custom functions, filters, and tests.
///
/// When a theme is configured, theme templates are loaded first as a base
/// layer. Local templates from `templates_dir` then overlay and override
/// any theme template with the same name.
pub fn setup_tera(
    templates_dir: &std::path::Path,
    config: &Config,
    sections: &HashMap<String, Section>,
) -> anyhow::Result<tera::Tera> {
    let mut tera = tera::Tera::default();

    // 1. Load theme templates as base layer (if theme is set)
    if let Some(ref theme_name) = config.theme {
        let theme = crate::themes::Theme::from_name(theme_name).ok_or_else(|| {
            anyhow::anyhow!(
                "Unknown theme '{}', available: {}",
                theme_name,
                crate::themes::Theme::available().join(", ")
            )
        })?;
        tera.add_raw_templates(theme.templates())?;
    }

    // 2. Overlay with local templates (local always wins)
    if templates_dir.exists() {
        let templates_glob = format!("{}/**/*.html", templates_dir.display());
        // Tera::parse errors if the glob matches no files. Only parse if
        // there are actually HTML files to load.
        match tera::Tera::parse(&templates_glob) {
            Ok(local) => {
                // tera.extend() skips templates that already exist, so we
                // re-add local templates as raw strings to override theme ones.
                let mut overrides = Vec::new();
                for name in local.templates.keys() {
                    let path = templates_dir.join(name);
                    if path.exists() {
                        let content = std::fs::read_to_string(&path)?;
                        overrides.push((name.clone(), content));
                    }
                }
                if !overrides.is_empty() {
                    let raw: Vec<(&str, &str)> = overrides
                        .iter()
                        .map(|(n, c)| (n.as_str(), c.as_str()))
                        .collect();
                    tera.add_raw_templates(raw)?;
                }
            }
            Err(e) => {
                let msg = e.to_string();
                // "No files matched" is expected when templates/ exists but
                // is empty (all templates come from the theme). Any other
                // parse error is a real problem.
                if !msg.contains("No files matched") {
                    return Err(anyhow::anyhow!("template error: {e}"));
                }
            }
        }
    }

    // Register custom functions
    register_functions(&mut tera, config, sections);

    // Register custom filters
    register_filters(&mut tera);

    // Register custom tests
    register_tests(&mut tera);

    Ok(tera)
}

fn register_functions(tera: &mut tera::Tera, config: &Config, sections: &HashMap<String, Section>) {
    // get_url function
    let base_url = config.base_url.clone();
    tera.register_function(
        "get_url",
        move |args: &HashMap<String, tera::Value>| -> tera::Result<tera::Value> {
            let path = args
                .get("path")
                .and_then(|v| v.as_str())
                .ok_or_else(|| tera::Error::msg("get_url requires a 'path' argument"))?;

            if let Some(content_path) = path.strip_prefix("@/") {
                let url = if content_path.ends_with("_index.md") {
                    let section_path =
                        content::section_url_path(&content::parent_dir(content_path));
                    format!("{base_url}{section_path}")
                } else {
                    let stem = std::path::Path::new(content_path)
                        .file_stem()
                        .unwrap_or_default()
                        .to_string_lossy();
                    let slug = slug::slugify(stem.as_ref());
                    let page_path =
                        content::page_url_path(&content::parent_dir(content_path), &slug);
                    format!("{base_url}{page_path}")
                };
                Ok(tera::Value::String(url))
            } else {
                // Static file or external URL
                if path.starts_with("http://") || path.starts_with("https://") {
                    Ok(tera::Value::String(path.to_string()))
                } else {
                    let url = format!("{}/{}", base_url, path.trim_start_matches('/'));
                    Ok(tera::Value::String(url))
                }
            }
        },
    );

    // get_section function
    let sections_clone = sections.clone();
    tera.register_function(
        "get_section",
        move |args: &HashMap<String, tera::Value>| -> tera::Result<tera::Value> {
            let path = args
                .get("path")
                .and_then(|v| v.as_str())
                .ok_or_else(|| tera::Error::msg("get_section requires a 'path' argument"))?;

            if let Some(section) = sections_clone.get(path) {
                let val = serde_json::to_value(section)
                    .map_err(|e| tera::Error::msg(format!("Serialization error: {e}")))?;
                Ok(val)
            } else {
                Err(tera::Error::msg(format!("Section not found: {path}")))
            }
        },
    );

    // get_taxonomy_url function
    let base_url2 = config.base_url.clone();
    tera.register_function(
        "get_taxonomy_url",
        move |args: &HashMap<String, tera::Value>| -> tera::Result<tera::Value> {
            let kind = args
                .get("kind")
                .and_then(|v| v.as_str())
                .ok_or_else(|| tera::Error::msg("get_taxonomy_url requires 'kind'"))?;
            let name = args
                .get("name")
                .and_then(|v| v.as_str())
                .ok_or_else(|| tera::Error::msg("get_taxonomy_url requires 'name'"))?;

            let slug = slug::slugify(name);
            let url = format!("{}/{kind}/{slug}/", base_url2);
            Ok(tera::Value::String(url))
        },
    );

    // now() function
    tera.register_function(
        "now",
        |_args: &HashMap<String, tera::Value>| -> tera::Result<tera::Value> {
            let now = chrono::Local::now().format("%Y-%m-%dT%H:%M:%S").to_string();
            Ok(tera::Value::String(now))
        },
    );
}

fn register_filters(tera: &mut tera::Tera) {
    // pluralize filter
    tera.register_filter(
        "pluralize",
        |value: &tera::Value, _args: &HashMap<String, tera::Value>| -> tera::Result<tera::Value> {
            let n = value
                .as_u64()
                .or_else(|| value.as_i64().map(|i| i as u64))
                .or_else(|| value.as_f64().map(|f| f as u64))
                .unwrap_or(0);
            if n == 1 {
                Ok(tera::Value::String(String::new()))
            } else {
                Ok(tera::Value::String("s".to_string()))
            }
        },
    );

    // slice filter with named 'end' parameter (Zola-compatible)
    tera.register_filter(
        "slice",
        |value: &tera::Value, args: &HashMap<String, tera::Value>| -> tera::Result<tera::Value> {
            let arr = value
                .as_array()
                .ok_or_else(|| tera::Error::msg("slice filter requires an array"))?;

            let start = args.get("start").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
            let end = args
                .get("end")
                .and_then(|v| v.as_u64())
                .map(|v| v as usize)
                .unwrap_or(arr.len());

            let end = end.min(arr.len());
            let start = start.min(end);

            Ok(tera::Value::Array(arr[start..end].to_vec()))
        },
    );

    // date filter (enhance the built-in one to handle our string dates)
    tera.register_filter(
        "date",
        |value: &tera::Value, args: &HashMap<String, tera::Value>| -> tera::Result<tera::Value> {
            let date_str = value
                .as_str()
                .ok_or_else(|| tera::Error::msg("date filter requires a string"))?;

            let format = args
                .get("format")
                .and_then(|v| v.as_str())
                .unwrap_or("%Y-%m-%d");

            // Try parsing various date formats
            if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(date_str, "%Y-%m-%dT%H:%M:%S") {
                return Ok(tera::Value::String(dt.format(format).to_string()));
            }
            if let Ok(d) = chrono::NaiveDate::parse_from_str(date_str, "%Y-%m-%d") {
                return Ok(tera::Value::String(d.format(format).to_string()));
            }

            // Return as-is if parsing fails
            Ok(tera::Value::String(date_str.to_string()))
        },
    );
}

fn register_tests(tera: &mut tera::Tera) {
    // starting_with test
    tera.register_tester(
        "starting_with",
        |value: Option<&tera::Value>, args: &[tera::Value]| -> tera::Result<bool> {
            let value = value.and_then(|v| v.as_str()).unwrap_or("");
            let prefix = args.first().and_then(|v| v.as_str()).unwrap_or("");

            Ok(value.starts_with(prefix))
        },
    );
}

/// Build Tera context for a page template
pub fn page_context(page: &Page, config: &Config) -> tera::Context {
    let mut ctx = tera::Context::new();
    ctx.insert("page", page);
    ctx.insert("config", &config_to_value(config));
    ctx.insert("section", &tera::Value::Null);
    ctx
}

/// Build Tera context for a section template
pub fn section_context(
    section: &Section,
    config: &Config,
    paginator: Option<&Paginator>,
) -> tera::Context {
    let mut ctx = tera::Context::new();
    ctx.insert("section", section);
    ctx.insert("config", &config_to_value(config));
    ctx.insert("page", &tera::Value::Null);
    if let Some(pag) = paginator {
        ctx.insert("paginator", pag);
    }
    ctx
}

/// Build Tera context for taxonomy list template
pub fn taxonomy_list_context(terms: &[TaxonomyTerm], config: &Config) -> tera::Context {
    let mut ctx = tera::Context::new();
    ctx.insert("terms", terms);
    ctx.insert("config", &config_to_value(config));
    ctx.insert("page", &tera::Value::Null);
    ctx.insert("section", &tera::Value::Null);
    ctx
}

/// Build Tera context for taxonomy single template
pub fn taxonomy_single_context(term: &TaxonomyTerm, config: &Config) -> tera::Context {
    let mut ctx = tera::Context::new();
    ctx.insert("term", term);
    ctx.insert("config", &config_to_value(config));
    ctx.insert("page", &tera::Value::Null);
    ctx.insert("section", &tera::Value::Null);
    ctx
}

/// Convert Config to a Tera-compatible Value
pub fn config_to_value(config: &Config) -> serde_json::Value {
    serde_json::to_value(config).expect("Config serialization should never fail")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Config;
    use crate::content::{Frontmatter, build_page, build_section};
    use tempfile::TempDir;

    fn minimal_config() -> Config {
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("config.toml"),
            r#"
base_url = "https://example.com"
title = "Test Site"

[extra]
author = "Tester"
"#,
        )
        .unwrap();
        Config::load(tmp.path()).unwrap()
    }

    fn minimal_page() -> Page {
        build_page(
            Frontmatter {
                title: Some("Test Page".into()),
                ..Default::default()
            },
            "Hello world".into(),
            "posts/test.md",
            "https://example.com",
        )
    }

    fn minimal_section() -> Section {
        build_section(
            Frontmatter {
                title: Some("Blog".into()),
                ..Default::default()
            },
            "Section content".into(),
            "posts/_index.md",
            "https://example.com",
        )
    }

    #[test]
    fn test_config_to_value_fields() {
        let config = minimal_config();
        let val = config_to_value(&config);
        assert_eq!(val["base_url"], "https://example.com");
        assert_eq!(val["title"], "Test Site");
        assert_eq!(val["extra"]["author"], "Tester");
        assert!(val["markdown"].is_object());
    }

    #[test]
    fn test_page_context_keys() {
        let config = minimal_config();
        let page = minimal_page();
        let ctx = page_context(&page, &config);
        let json = ctx.into_json();
        assert!(json.get("page").is_some());
        assert!(json.get("config").is_some());
        assert!(json.get("section").unwrap().is_null());
    }

    #[test]
    fn test_section_context_keys() {
        let config = minimal_config();
        let section = minimal_section();
        let ctx = section_context(&section, &config, None);
        let json = ctx.into_json();
        assert!(json.get("section").is_some());
        assert!(json.get("config").is_some());
        assert!(json.get("page").unwrap().is_null());
    }

    #[test]
    fn test_section_context_with_paginator() {
        let config = minimal_config();
        let section = minimal_section();
        let pag = Paginator {
            pages: vec![],
            current_index: 1,
            number_pagers: 3,
            previous: None,
            next: Some("https://example.com/posts/page/2/".into()),
            first: "https://example.com/posts/".into(),
            last: "https://example.com/posts/page/3/".into(),
        };
        let ctx = section_context(&section, &config, Some(&pag));
        let json = ctx.into_json();
        let p = json.get("paginator").unwrap();
        assert_eq!(p["current_index"], 1);
        assert_eq!(p["number_pagers"], 3);
    }

    #[test]
    fn test_pluralize_filter() {
        let tmp = TempDir::new().unwrap();
        let tmpl_dir = tmp.path().join("templates");
        std::fs::create_dir_all(&tmpl_dir).unwrap();
        std::fs::write(tmpl_dir.join("test.html"), "{{ count | pluralize }}").unwrap();
        let config = minimal_config();
        let sections = HashMap::new();
        let tera = setup_tera(&tmpl_dir, &config, &sections).unwrap();
        let mut ctx = tera::Context::new();
        ctx.insert("count", &1);
        let result = tera.render("test.html", &ctx).unwrap();
        assert_eq!(result, "");
        ctx.insert("count", &5);
        let result = tera.render("test.html", &ctx).unwrap();
        assert_eq!(result, "s");
    }

    #[test]
    fn test_slice_filter() {
        let tmp = TempDir::new().unwrap();
        let tmpl_dir = tmp.path().join("templates");
        std::fs::create_dir_all(&tmpl_dir).unwrap();
        std::fs::write(
            tmpl_dir.join("test.html"),
            r#"{% for item in items | slice(end=2) %}{{ item }}{% endfor %}"#,
        )
        .unwrap();
        let config = minimal_config();
        let sections = HashMap::new();
        let tera = setup_tera(&tmpl_dir, &config, &sections).unwrap();
        let mut ctx = tera::Context::new();
        ctx.insert("items", &vec!["a", "b", "c", "d"]);
        let result = tera.render("test.html", &ctx).unwrap();
        assert_eq!(result, "ab");
    }

    #[test]
    fn test_date_filter() {
        let tmp = TempDir::new().unwrap();
        let tmpl_dir = tmp.path().join("templates");
        std::fs::create_dir_all(&tmpl_dir).unwrap();
        std::fs::write(
            tmpl_dir.join("test.html"),
            r#"{{ d | date(format="%B %d, %Y") }}"#,
        )
        .unwrap();
        let config = minimal_config();
        let sections = HashMap::new();
        let tera = setup_tera(&tmpl_dir, &config, &sections).unwrap();
        let mut ctx = tera::Context::new();
        ctx.insert("d", "2025-06-15");
        let result = tera.render("test.html", &ctx).unwrap();
        assert_eq!(result, "June 15, 2025");
    }

    #[test]
    fn test_starting_with_tester() {
        let tmp = TempDir::new().unwrap();
        let tmpl_dir = tmp.path().join("templates");
        std::fs::create_dir_all(&tmpl_dir).unwrap();
        std::fs::write(
            tmpl_dir.join("test.html"),
            r#"{% if path is starting_with("/blog") %}yes{% else %}no{% endif %}"#,
        )
        .unwrap();
        let config = minimal_config();
        let sections = HashMap::new();
        let tera = setup_tera(&tmpl_dir, &config, &sections).unwrap();
        let mut ctx = tera::Context::new();
        ctx.insert("path", "/blog/post");
        assert_eq!(tera.render("test.html", &ctx).unwrap(), "yes");
        ctx.insert("path", "/about");
        assert_eq!(tera.render("test.html", &ctx).unwrap(), "no");
    }

    #[test]
    fn test_get_url_content_path() {
        let tmp = TempDir::new().unwrap();
        let tmpl_dir = tmp.path().join("templates");
        std::fs::create_dir_all(&tmpl_dir).unwrap();
        std::fs::write(
            tmpl_dir.join("test.html"),
            r#"{{ get_url(path="@/posts/hello.md") | safe }}"#,
        )
        .unwrap();
        let config = minimal_config();
        let sections = HashMap::new();
        let tera = setup_tera(&tmpl_dir, &config, &sections).unwrap();
        let ctx = tera::Context::new();
        let result = tera.render("test.html", &ctx).unwrap();
        assert_eq!(result, "https://example.com/posts/hello/");
    }

    #[test]
    fn test_get_url_static_path() {
        let tmp = TempDir::new().unwrap();
        let tmpl_dir = tmp.path().join("templates");
        std::fs::create_dir_all(&tmpl_dir).unwrap();
        std::fs::write(
            tmpl_dir.join("test.html"),
            r#"{{ get_url(path="/img/photo.png") | safe }}"#,
        )
        .unwrap();
        let config = minimal_config();
        let sections = HashMap::new();
        let tera = setup_tera(&tmpl_dir, &config, &sections).unwrap();
        let ctx = tera::Context::new();
        let result = tera.render("test.html", &ctx).unwrap();
        assert_eq!(result, "https://example.com/img/photo.png");
    }
}