tron 2.1.0

A rust based template system built for speed and simplicity.
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
//! Template loading utilities for the Tron template engine.
//!
//! This module provides advanced template loading functionality including
//! watching for file changes, lazy loading, and template discovery.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use crate::error::{Result, TronError};
use crate::template::TronTemplate;
use crate::cache::{TemplateCache, CacheConfig};
use walkdir::WalkDir;
use glob::glob;

/// Configuration for template loading behavior.
#[derive(Debug, Clone)]
pub struct LoaderConfig {
    /// Whether to recursively search subdirectories
    pub recursive: bool,
    /// File extensions to consider as templates
    pub extensions: Vec<String>,
    /// Whether to track file modification times for reloading
    pub track_changes: bool,
    /// Maximum directory depth for recursive searches
    pub max_depth: Option<usize>,
    /// Whether to enable template caching
    pub enable_caching: bool,
    /// Cache configuration (if caching is enabled)
    pub cache_config: CacheConfig,
}

impl Default for LoaderConfig {
    fn default() -> Self {
        Self {
            recursive: true,
            extensions: vec!["tron".to_string(), "tpl".to_string(), "template".to_string()],
            track_changes: false,
            max_depth: None,
            enable_caching: true,
            cache_config: CacheConfig::default(),
        }
    }
}

/// Metadata about a loaded template.
#[derive(Debug, Clone)]
pub struct TemplateMetadata {
    /// File path of the template
    pub path: PathBuf,
    /// Last modification time
    pub modified: Option<SystemTime>,
    /// Template size in bytes
    pub size: u64,
}

/// Advanced template loader with caching and file watching capabilities.
///
/// `TemplateLoader` provides efficient template loading with features like:
/// - Template caching to avoid repeated file I/O
/// - File modification tracking for automatic reloading
/// - Flexible search patterns and directory traversal
/// - Template discovery and enumeration
///
/// # Examples
///
/// Basic template loading:
///
/// ```
/// use tron::TemplateLoader;
///
/// let mut loader = TemplateLoader::new();
/// let templates = loader.load_from_directory("templates/").unwrap();
/// 
/// for (name, template) in templates {
///     println!("Loaded: {} with {} placeholders", 
///              name, template.placeholder_names().len());
/// }
/// ```
///
/// With custom configuration:
///
/// ```
/// use tron::{TemplateLoader, LoaderConfig};
///
/// let config = LoaderConfig {
///     recursive: false,
///     extensions: vec!["tron".to_string()],
///     track_changes: true,
///     max_depth: Some(2),
///     enable_caching: true,
///     cache_config: Default::default(),
/// };
///
/// let loader = TemplateLoader::with_config(config);
/// let templates = loader.discover_templates("src/").unwrap();
/// ```
pub struct TemplateLoader {
    config: LoaderConfig,
    cache: HashMap<PathBuf, (TronTemplate, TemplateMetadata)>,
    template_cache: Option<TemplateCache>,
}

impl TemplateLoader {
    /// Create a new template loader with default configuration.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::TemplateLoader;
    ///
    /// let loader = TemplateLoader::new();
    /// ```
    pub fn new() -> Self {
        let config = LoaderConfig::default();
        let template_cache = if config.enable_caching {
            Some(TemplateCache::with_config(config.cache_config.clone()))
        } else {
            None
        };
        
        Self {
            config,
            cache: HashMap::new(),
            template_cache,
        }
    }

    /// Create a template loader with custom configuration.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::{TemplateLoader, LoaderConfig};
    ///
    /// let config = LoaderConfig {
    ///     recursive: false,
    ///     extensions: vec!["tpl".to_string()],
    ///     ..LoaderConfig::default()
    /// };
    ///
    /// let loader = TemplateLoader::with_config(config);
    /// ```
    pub fn with_config(config: LoaderConfig) -> Self {
        let template_cache = if config.enable_caching {
            Some(TemplateCache::with_config(config.cache_config.clone()))
        } else {
            None
        };
        
        Self {
            config,
            cache: HashMap::new(),
            template_cache,
        }
    }

    /// Load templates from a directory using the loader's configuration.
    ///
    /// This respects the loader's settings for recursion, file extensions,
    /// and caching.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use tron::TemplateLoader;
    ///
    /// let mut loader = TemplateLoader::new();
    /// let templates = loader.load_from_directory("templates/").unwrap();
    /// println!("Loaded {} templates", templates.len());
    /// ```
    ///
    /// # Errors
    ///
    /// Returns error if directory cannot be read or templates cannot be parsed.
    pub fn load_from_directory<P: AsRef<Path>>(&mut self, dir: P) -> Result<Vec<(String, TronTemplate)>> {
        let dir_path = dir.as_ref();
        let mut templates = Vec::new();

        if !dir_path.is_dir() {
            return Err(TronError::Io(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                format!("Directory not found: {}", dir_path.display())
            )));
        }

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

        let walker = if let Some(max_depth) = self.config.max_depth {
            walker.max_depth(max_depth)
        } else {
            walker
        };

        for entry in walker {
            let entry = entry.map_err(|e| TronError::Io(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Failed to walk directory: {}", e)
            )))?;
            let path = entry.path();

            if path.is_file() {
                if let Some(extension) = path.extension() {
                    let ext_str = extension.to_string_lossy().to_lowercase();
                    if self.config.extensions.contains(&ext_str) {
                        let template = self.load_template(path)?;
                        let name = path.file_name()
                            .unwrap()
                            .to_string_lossy()
                            .to_string();
                        templates.push((name, template));
                    }
                }
            }
        }

        Ok(templates)
    }

    /// Load templates matching a glob pattern.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use tron::TemplateLoader;
    ///
    /// let mut loader = TemplateLoader::new();
    /// let templates = loader.load_from_glob("**/*.tron").unwrap();
    /// ```
    pub fn load_from_glob(&mut self, pattern: &str) -> Result<Vec<(String, TronTemplate)>> {
        let mut templates = Vec::new();

        let glob_result = glob(pattern)
            .map_err(|e| TronError::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                format!("Invalid glob pattern '{}': {}", pattern, e)
            )))?;

        for entry in glob_result {
            let path = entry.map_err(|e| TronError::Io(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Glob error: {}", e)
            )))?;
            if path.is_file() {
                // Check if extension is allowed
                if let Some(extension) = path.extension() {
                    let ext_str = extension.to_string_lossy().to_lowercase();
                    if self.config.extensions.contains(&ext_str) {
                        let template = self.load_template(&path)?;
                        let name = path.file_name()
                            .unwrap()
                            .to_string_lossy()
                            .to_string();
                        templates.push((name, template));
                    }
                }
            }
        }

        Ok(templates)
    }

    /// Discover all templates in a given path and its subdirectories.
    ///
    /// This returns metadata about templates without loading them,
    /// useful for template discovery and indexing.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use tron::TemplateLoader;
    ///
    /// let loader = TemplateLoader::new();
    /// let discovered = loader.discover_templates("src/").unwrap();
    /// 
    /// for (name, metadata) in discovered {
    ///     println!("Found template: {} ({} bytes)", name, metadata.size);
    /// }
    /// ```
    pub fn discover_templates<P: AsRef<Path>>(&self, dir: P) -> Result<Vec<(String, TemplateMetadata)>> {
        let dir_path = dir.as_ref();
        let mut templates = Vec::new();

        if !dir_path.is_dir() {
            return Err(TronError::Io(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                format!("Directory not found: {}", dir_path.display())
            )));
        }

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

        let walker = if let Some(max_depth) = self.config.max_depth {
            walker.max_depth(max_depth)
        } else {
            walker
        };

        for entry in walker {
            let entry = entry.map_err(|e| TronError::Io(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Failed to walk directory: {}", e)
            )))?;
            let path = entry.path();

            if path.is_file() {
                if let Some(extension) = path.extension() {
                    let ext_str = extension.to_string_lossy().to_lowercase();
                    if self.config.extensions.contains(&ext_str) {
                        let metadata = std::fs::metadata(path)?;
                        let template_metadata = TemplateMetadata {
                            path: path.to_path_buf(),
                            modified: metadata.modified().ok(),
                            size: metadata.len(),
                        };
                        let name = path.file_name()
                            .unwrap()
                            .to_string_lossy()
                            .to_string();
                        templates.push((name, template_metadata));
                    }
                }
            }
        }

        Ok(templates)
    }

    /// Load a single template, using cache if available and change tracking is enabled.
    fn load_template<P: AsRef<Path>>(&mut self, path: P) -> Result<TronTemplate> {
        let path = path.as_ref();

        // Try the new TemplateCache first if enabled
        if let Some(ref template_cache) = self.template_cache {
            if let Some(cached_template) = template_cache.get_by_path(path) {
                return Ok(cached_template);
            }
        }

        // Fall back to old cache if tracking changes
        if self.config.track_changes {
            if let Some((cached_template, metadata)) = self.cache.get(path) {
                // Check if file has been modified
                if let Ok(file_metadata) = std::fs::metadata(path) {
                    if let (Some(cached_modified), Ok(current_modified)) = 
                        (metadata.modified, file_metadata.modified()) {
                        if current_modified <= cached_modified {
                            // File hasn't been modified, return cached version
                            return Ok(cached_template.clone());
                        }
                    }
                }
            }
        }

        // Load template from file
        let template = TronTemplate::from_file(path)?;

        // Cache in the new TemplateCache if enabled
        if let Some(ref template_cache) = self.template_cache {
            template_cache.insert_template(template.clone())?;
        }

        // Cache in old cache if tracking changes
        if self.config.track_changes {
            if let Ok(file_metadata) = std::fs::metadata(path) {
                let template_metadata = TemplateMetadata {
                    path: path.to_path_buf(),
                    modified: file_metadata.modified().ok(),
                    size: file_metadata.len(),
                };
                self.cache.insert(path.to_path_buf(), (template.clone(), template_metadata));
            }
        }

        Ok(template)
    }

    /// Clear the template cache.
    ///
    /// This forces all templates to be reloaded from disk on the next access.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::TemplateLoader;
    ///
    /// let mut loader = TemplateLoader::new();
    /// // ... load some templates
    /// loader.clear_cache();
    /// // Templates will be reloaded from disk
    /// ```
    pub fn clear_cache(&mut self) {
        self.cache.clear();
        if let Some(ref template_cache) = self.template_cache {
            template_cache.clear();
        }
    }

    /// Get the current cache size (number of cached templates).
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::TemplateLoader;
    ///
    /// let loader = TemplateLoader::new();
    /// println!("Cache contains {} templates", loader.cache_size());
    /// ```
    pub fn cache_size(&self) -> usize {
        if let Some(ref template_cache) = self.template_cache {
            template_cache.size()
        } else {
            self.cache.len()
        }
    }

    /// Check if a template is cached.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::TemplateLoader;
    /// use std::path::Path;
    ///
    /// let loader = TemplateLoader::new();
    /// let path = Path::new("templates/example.tron");
    /// 
    /// if loader.is_cached(&path) {
    ///     println!("Template is in cache");
    /// }
    /// ```
    pub fn is_cached<P: AsRef<Path>>(&self, path: P) -> bool {
        if let Some(ref template_cache) = self.template_cache {
            template_cache.is_cached(path.as_ref())
        } else {
            self.cache.contains_key(path.as_ref())
        }
    }
    
    /// Get cache statistics (if available).
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::TemplateLoader;
    ///
    /// let loader = TemplateLoader::new();
    /// if let Some(stats) = loader.cache_stats() {
    ///     println!("Cache hit ratio: {:.2}%", stats.hit_ratio() * 100.0);
    /// }
    /// ```
    pub fn cache_stats(&self) -> Option<crate::cache::CacheStats> {
        if let Some(ref template_cache) = self.template_cache {
            template_cache.stats()
        } else {
            None
        }
    }
    
    /// Clean up expired templates from the cache.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::TemplateLoader;
    ///
    /// let loader = TemplateLoader::new();
    /// // ... load some templates
    /// loader.cleanup_expired_cache(); // Remove expired entries
    /// ```
    pub fn cleanup_expired_cache(&self) {
        if let Some(ref template_cache) = self.template_cache {
            template_cache.cleanup_expired();
        }
    }
}

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

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

    #[test]
    fn test_loader_config_default() {
        let config = LoaderConfig::default();
        assert!(config.recursive);
        assert_eq!(config.extensions, vec!["tron", "tpl", "template"]);
        assert!(!config.track_changes);
        assert_eq!(config.max_depth, None);
    }

    #[test]
    fn test_template_loader_new() {
        let loader = TemplateLoader::new();
        assert_eq!(loader.cache_size(), 0);
        assert!(loader.config.recursive);
    }

    #[test]
    #[cfg(test)]
    fn test_load_from_directory() -> Result<()> {
        let mut loader = TemplateLoader::new();
        let templates = loader.load_from_directory("templates")?;
        
        // Should load templates from the templates directory
        assert!(!templates.is_empty());
        
        Ok(())
    }

    #[test]
    #[cfg(test)] 
    fn test_discover_templates() -> Result<()> {
        let loader = TemplateLoader::new();
        let discovered = loader.discover_templates("templates")?;
        
        // Should discover templates without loading them
        assert!(!discovered.is_empty());
        
        // Check metadata is populated
        for (_name, metadata) in discovered {
            assert!(metadata.path.exists());
            assert!(metadata.size > 0);
        }
        
        Ok(())
    }

    #[test]
    fn test_loader_with_config() {
        let config = LoaderConfig {
            recursive: false,
            extensions: vec!["tron".to_string()],
            track_changes: true,
            max_depth: Some(1),
            enable_caching: true,
            cache_config: CacheConfig::default(),
        };
        
        let loader = TemplateLoader::with_config(config);
        assert!(!loader.config.recursive);
        assert_eq!(loader.config.extensions, vec!["tron"]);
        assert!(loader.config.track_changes);
        assert_eq!(loader.config.max_depth, Some(1));
        assert!(loader.config.enable_caching);
        assert!(loader.template_cache.is_some());
    }

    #[test]
    fn test_cache_operations() {
        let mut loader = TemplateLoader::new();
        assert_eq!(loader.cache_size(), 0);
        
        loader.clear_cache();
        assert_eq!(loader.cache_size(), 0);
        
        // is_cached should return false for non-existent paths
        assert!(!loader.is_cached("nonexistent.tron"));
    }
}