clnrm-template 1.3.0

Cleanroom Testing Framework - Template Engine
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
//! Template discovery and auto-loading system
//!
//! Provides convenient APIs for discovering and loading templates from:
//! - Directories (recursive)
//! - Glob patterns
//! - File paths
//! - Template collections/namespaces

use crate::error::{Result, TemplateError};
use crate::renderer::TemplateRenderer;
use std::collections::HashMap;
use std::path::{Path, PathBuf};

/// Template discovery and loading system
///
/// Provides fluent API for discovering templates from various sources:
/// - Auto-discovery in directories
/// - Glob pattern matching
/// - Template namespaces
/// - Hot-reload support
#[derive(Debug)]
pub struct TemplateDiscovery {
    /// Base search paths for template discovery
    search_paths: Vec<PathBuf>,
    /// Template namespace mappings (namespace -> template content)
    namespaces: HashMap<String, String>,
    /// Glob patterns for template inclusion
    glob_patterns: Vec<String>,
    /// Enable recursive directory scanning
    recursive: bool,
    /// File extensions to include (default: .toml, .tera, .tpl)
    extensions: Vec<String>,
    /// Enable hot-reload (watch for file changes)
    hot_reload: bool,
    /// Template organization strategy
    organization: TemplateOrganization,
}

/// Template organization strategies
#[derive(Debug, Clone)]
pub enum TemplateOrganization {
    /// Flat organization (all templates in single namespace)
    Flat,
    /// Hierarchical organization (templates organized by directory structure)
    Hierarchical,
    /// Custom organization with prefixes
    Custom { prefix: String },
}

impl Default for TemplateDiscovery {
    fn default() -> Self {
        Self {
            search_paths: Vec::new(),
            namespaces: HashMap::new(),
            glob_patterns: Vec::new(),
            recursive: true,
            extensions: vec![
                "toml".to_string(),
                "tera".to_string(),
                "tpl".to_string(),
                "template".to_string(),
            ],
            hot_reload: false,
            organization: TemplateOrganization::Hierarchical,
        }
    }
}

impl TemplateDiscovery {
    /// Create new template discovery instance
    pub fn new() -> Self {
        Self::default()
    }

    /// Add search path for template discovery
    ///
    /// # Arguments
    /// * `path` - Directory path to search for templates
    pub fn with_search_path<P: AsRef<Path>>(mut self, path: P) -> Self {
        self.search_paths.push(path.as_ref().to_path_buf());
        self
    }

    /// Add multiple search paths
    pub fn with_search_paths<I, P>(mut self, paths: I) -> Self
    where
        I: IntoIterator<Item = P>,
        P: AsRef<Path>,
    {
        for path in paths {
            self.search_paths.push(path.as_ref().to_path_buf());
        }
        self
    }

    /// Add glob pattern for template inclusion
    ///
    /// # Arguments
    /// * `pattern` - Glob pattern (e.g., "**/*.toml", "tests/**/*.tera")
    pub fn with_glob_pattern(mut self, pattern: &str) -> Self {
        self.glob_patterns.push(pattern.to_string());
        self
    }

    /// Enable/disable recursive directory scanning
    pub fn recursive(mut self, recursive: bool) -> Self {
        self.recursive = recursive;
        self
    }

    /// Set file extensions to include in discovery
    pub fn with_extensions<I, S>(mut self, extensions: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.extensions = extensions.into_iter().map(|s| s.into()).collect();
        self
    }

    /// Enable hot-reload for template files
    pub fn hot_reload(mut self, enabled: bool) -> Self {
        self.hot_reload = enabled;
        self
    }

    /// Set template organization strategy
    pub fn with_organization(mut self, organization: TemplateOrganization) -> Self {
        self.organization = organization;
        self
    }

    /// Add template to namespace
    ///
    /// # Arguments
    /// * `namespace` - Namespace name (e.g., "macros", "partials")
    /// * `content` - Template content
    pub fn with_namespace<S: Into<String>>(mut self, namespace: S, content: S) -> Self {
        self.namespaces.insert(namespace.into(), content.into());
        self
    }

    /// Discover and load all templates
    ///
    /// Returns a TemplateLoader with all discovered templates ready for rendering
    pub fn load(self) -> Result<TemplateLoader> {
        let mut templates = HashMap::new();

        // Load namespace templates first (highest priority)
        for (namespace, content) in &self.namespaces {
            templates.insert(namespace.to_string(), content.to_string());
        }

        // Discover templates from search paths
        for search_path in &self.search_paths {
            self.discover_from_path(search_path, &mut templates)?;
        }

        // Discover templates from glob patterns
        for pattern in &self.glob_patterns {
            self.discover_from_glob(pattern, &mut templates)?;
        }

        Ok(TemplateLoader {
            templates,
            hot_reload: self.hot_reload,
            organization: self.organization,
        })
    }

    /// Discover templates from a directory path
    fn discover_from_path(
        &self,
        path: &Path,
        templates: &mut HashMap<String, String>,
    ) -> Result<()> {
        if !path.exists() {
            return Ok(()); // Skip non-existent paths
        }

        if path.is_file() {
            // Single file
            if self.should_include_file(path) {
                let name = self.template_name_from_path(path);
                let content = std::fs::read_to_string(path).map_err(|e| {
                    TemplateError::IoError(format!(
                        "Failed to read template file {:?}: {}",
                        path, e
                    ))
                })?;
                templates.insert(name, content);
            }
            return Ok(());
        }

        // Directory scanning
        self.scan_directory(path, templates)
    }

    /// Discover templates from glob pattern
    fn discover_from_glob(
        &self,
        pattern: &str,
        templates: &mut HashMap<String, String>,
    ) -> Result<()> {
        use globset::{Glob, GlobSetBuilder};

        let glob = Glob::new(pattern).map_err(|e| {
            TemplateError::ConfigError(format!("Invalid glob pattern '{}': {}", pattern, e))
        })?;

        let glob_set = GlobSetBuilder::new().add(glob).build().map_err(|e| {
            TemplateError::ConfigError(format!("Failed to build glob set for '{}': {}", pattern, e))
        })?;

        for search_path in &self.search_paths {
            self.scan_path_with_glob(search_path, &glob_set, templates)?;
        }

        Ok(())
    }

    /// Scan directory for template files
    fn scan_directory(&self, dir: &Path, templates: &mut HashMap<String, String>) -> Result<()> {
        use walkdir::WalkDir;

        let walker = if self.recursive {
            WalkDir::new(dir)
        } else {
            WalkDir::new(dir).max_depth(1)
        };

        for entry in walker {
            let entry = entry.map_err(|e| {
                TemplateError::IoError(format!("Failed to read directory entry: {}", e))
            })?;

            if entry.file_type().is_file() && self.should_include_file(entry.path()) {
                let name = self.template_name_from_path(entry.path());
                let content = std::fs::read_to_string(entry.path()).map_err(|e| {
                    TemplateError::IoError(format!(
                        "Failed to read template file {:?}: {}",
                        entry.path(),
                        e
                    ))
                })?;

                templates.insert(name, content);
            }
        }

        Ok(())
    }

    /// Scan path with glob pattern
    fn scan_path_with_glob(
        &self,
        path: &Path,
        glob_set: &globset::GlobSet,
        templates: &mut HashMap<String, String>,
    ) -> Result<()> {
        use walkdir::WalkDir;

        let walker = if self.recursive {
            WalkDir::new(path)
        } else {
            WalkDir::new(path).max_depth(1)
        };

        for entry in walker {
            let entry = entry.map_err(|e| {
                TemplateError::IoError(format!("Failed to read directory entry: {}", e))
            })?;

            if entry.file_type().is_file() {
                let path_str = entry.path().to_string_lossy();
                if glob_set.is_match(&*path_str) && self.should_include_file(entry.path()) {
                    let name = self.template_name_from_path(entry.path());
                    let content = std::fs::read_to_string(entry.path()).map_err(|e| {
                        TemplateError::IoError(format!(
                            "Failed to read template file {:?}: {}",
                            entry.path(),
                            e
                        ))
                    })?;

                    templates.insert(name, content);
                }
            }
        }

        Ok(())
    }

    /// Check if file should be included based on extension
    fn should_include_file(&self, path: &Path) -> bool {
        if let Some(extension) = path.extension().and_then(|s| s.to_str()) {
            self.extensions.contains(&extension.to_string())
        } else {
            false
        }
    }

    /// Generate template name from file path
    fn template_name_from_path(&self, path: &Path) -> String {
        // Remove extension and convert path separators to dots
        let stem = path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("unknown");

        // For relative paths within search paths, use relative structure
        for search_path in &self.search_paths {
            if let Ok(relative_path) = path.strip_prefix(search_path) {
                let relative_str = relative_path.to_string_lossy().replace(['/', '\\'], ".");
                let name_without_ext = Path::new(&relative_str)
                    .file_stem()
                    .and_then(|s| s.to_str())
                    .unwrap_or(stem);

                return match &self.organization {
                    TemplateOrganization::Flat => name_without_ext.to_string(),
                    TemplateOrganization::Hierarchical => {
                        // Use full relative path as template name
                        let parent = relative_path
                            .parent()
                            .and_then(|p| p.to_str())
                            .unwrap_or("");
                        if parent.is_empty() {
                            name_without_ext.to_string()
                        } else {
                            format!("{}.{}", parent.replace(['/', '\\'], "."), name_without_ext)
                        }
                    }
                    TemplateOrganization::Custom { prefix } => {
                        format!("{}.{}", prefix, name_without_ext)
                    }
                };
            }
        }

        stem.to_string()
    }
}

/// Template loader with loaded templates ready for rendering
///
/// Provides template rendering with loaded template collection.
/// Supports hot-reload if enabled during discovery.
#[derive(Debug)]
pub struct TemplateLoader {
    /// Loaded templates (name -> content)
    pub(crate) templates: HashMap<String, String>,
    /// Hot-reload enabled
    #[allow(dead_code)]
    hot_reload: bool,
    /// Template organization strategy
    organization: TemplateOrganization,
}

impl Default for TemplateLoader {
    fn default() -> Self {
        Self::new()
    }
}

impl TemplateLoader {
    /// Create new template loader
    pub fn new() -> Self {
        Self {
            templates: HashMap::new(),
            hot_reload: false,
            organization: TemplateOrganization::Hierarchical,
        }
    }

    /// Get template content by name
    pub fn get_template(&self, name: &str) -> Option<&str> {
        self.templates.get(name).map(|s| s.as_str())
    }

    /// Check if template exists
    pub fn has_template(&self, name: &str) -> bool {
        self.templates.contains_key(name)
    }

    /// List all available template names
    pub fn template_names(&self) -> Vec<&str> {
        self.templates.keys().map(|s| s.as_str()).collect()
    }

    /// List templates by category (for hierarchical organization)
    pub fn templates_by_category(&self) -> HashMap<String, Vec<String>> {
        let mut categories = HashMap::new();

        for name in self.templates.keys() {
            let category = if let Some(dot_pos) = name.rfind('.') {
                name[..dot_pos].to_string()
            } else {
                "root".to_string()
            };

            categories
                .entry(category)
                .or_insert_with(Vec::new)
                .push(name.clone());
        }

        categories
    }

    /// Create template renderer with loaded templates
    ///
    /// # Arguments
    /// * `context` - Template context for rendering
    /// * `determinism` - Optional determinism configuration
    pub fn create_renderer(
        &self,
        context: crate::context::TemplateContext,
    ) -> Result<TemplateRenderer> {
        let mut renderer = TemplateRenderer::new()?;

        // Add all loaded templates
        for (name, content) in &self.templates {
            renderer.add_template(name, content).map_err(|e| {
                TemplateError::RenderError(format!("Failed to add template '{}': {}", name, e))
            })?;
        }

        Ok(renderer.with_context(context))
    }

    /// Render template by name
    ///
    /// # Arguments
    /// * `name` - Template name
    /// * `context` - Template context
    /// * `determinism` - Optional determinism configuration
    pub fn render(&self, name: &str, context: crate::context::TemplateContext) -> Result<String> {
        let mut renderer = self.create_renderer(context)?;
        renderer.render_str(&self.templates[name], name)
    }

    /// Render template with user variables
    ///
    /// Convenience method for simple rendering with user vars
    pub fn render_with_vars(
        &self,
        name: &str,
        user_vars: std::collections::HashMap<String, serde_json::Value>,
    ) -> Result<String> {
        let mut context = crate::context::TemplateContext::with_defaults();
        context.merge_user_vars(user_vars);
        self.render(name, context)
    }

    /// Save all templates to files (for template generation)
    ///
    /// # Arguments
    /// * `output_dir` - Directory to save templates to
    pub fn save_to_directory<P: AsRef<Path>>(&self, output_dir: P) -> Result<()> {
        let output_dir = output_dir.as_ref();

        // Create output directory if it doesn't exist
        std::fs::create_dir_all(output_dir).map_err(|e| {
            TemplateError::IoError(format!("Failed to create output directory: {}", e))
        })?;

        for (name, content) in &self.templates {
            let file_path = self.template_path_from_name(name, output_dir);
            std::fs::write(&file_path, content).map_err(|e| {
                TemplateError::IoError(format!("Failed to write template '{}': {}", name, e))
            })?;
        }

        Ok(())
    }

    /// Convert template name back to file path
    fn template_path_from_name(&self, name: &str, base_dir: &Path) -> PathBuf {
        match &self.organization {
            TemplateOrganization::Flat => base_dir.join(format!("{}.toml", name)),
            TemplateOrganization::Hierarchical => {
                // Convert dots back to path separators
                let path_str = name.replace('.', "/");
                base_dir.join(format!("{}.toml", path_str))
            }
            TemplateOrganization::Custom { prefix } => {
                // Remove prefix and convert to path
                let path_part = if name.starts_with(&format!("{}.", prefix)) {
                    &name[prefix.len() + 1..]
                } else {
                    name
                };
                let path_str = path_part.replace('.', "/");
                base_dir.join(format!("{}.toml", path_str))
            }
        }
    }
}

/// Fluent API for template loading
pub struct TemplateLoaderBuilder {
    discovery: TemplateDiscovery,
}

impl TemplateLoaderBuilder {
    /// Start building template loader
    pub fn new() -> Self {
        Self {
            discovery: TemplateDiscovery::new(),
        }
    }

    /// Add search path
    pub fn search_path<P: AsRef<Path>>(mut self, path: P) -> Self {
        self.discovery
            .search_paths
            .push(path.as_ref().to_path_buf());
        self
    }

    /// Add glob pattern
    pub fn glob_pattern(mut self, pattern: &str) -> Self {
        self.discovery.glob_patterns.push(pattern.to_string());
        self
    }

    /// Add namespace template
    pub fn namespace<S: Into<String>>(mut self, name: S, content: S) -> Self {
        self.discovery
            .namespaces
            .insert(name.into(), content.into());
        self
    }

    /// Enable hot reload
    pub fn hot_reload(mut self) -> Self {
        self.discovery.hot_reload = true;
        self
    }

    /// Set organization strategy
    pub fn organization(mut self, organization: TemplateOrganization) -> Self {
        self.discovery.organization = organization;
        self
    }

    /// Build the template loader
    pub fn build(self) -> Result<TemplateLoader> {
        self.discovery.load()
    }
}

impl Default for TemplateLoaderBuilder {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_template_discovery_basic() -> Result<()> {
        let temp_dir = tempdir()?;
        let template_file = temp_dir.path().join("test.toml");
        std::fs::write(&template_file, "name = \"{{ test_var }}\"")?;

        let discovery = TemplateDiscovery::new()
            .with_search_path(&temp_dir)
            .recursive(false);

        let loader = discovery.load()?;

        assert!(loader.has_template("test"));
        assert_eq!(
            loader.get_template("test"),
            Some("name = \"{{ test_var }}\"")
        );

        Ok(())
    }

    #[test]
    fn test_template_discovery_with_namespace() -> Result<()> {
        let discovery = TemplateDiscovery::new()
            .with_namespace("macros", "{% macro test() %}Hello{% endmacro %}");

        let loader = discovery.load()?;

        assert!(loader.has_template("macros"));
        assert_eq!(
            loader.get_template("macros"),
            Some("{% macro test() %}Hello{% endmacro %}")
        );

        Ok(())
    }

    #[test]
    fn test_template_loader_rendering() -> Result<()> {
        let temp_dir = tempdir()?;
        let template_file = temp_dir.path().join("config.toml");
        std::fs::write(&template_file, "service = \"{{ svc }}\"")?;

        let discovery = TemplateDiscovery::new().with_search_path(&temp_dir);

        let loader = discovery.load()?;

        let mut vars = std::collections::HashMap::new();
        vars.insert(
            "svc".to_string(),
            serde_json::Value::String("test-service".to_string()),
        );

        let result = loader.render_with_vars("config", vars)?;
        assert_eq!(result.trim(), "service = \"test-service\"");

        Ok(())
    }

    #[test]
    fn test_hierarchical_organization() -> Result<()> {
        let temp_dir = tempdir()?;
        let subdir = temp_dir.path().join("services");
        std::fs::create_dir_all(&subdir)?;

        let template_file = subdir.join("api.toml");
        std::fs::write(&template_file, "service = \"api\"")?;

        let discovery = TemplateDiscovery::new()
            .with_search_path(&temp_dir)
            .with_organization(TemplateOrganization::Hierarchical);

        let loader = discovery.load()?;

        assert!(loader.has_template("services.api"));

        Ok(())
    }
}