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
//! Async template rendering support
//!
//! Provides async versions of template rendering functions for use in async applications:
//! - Async template rendering
//! - Async file operations
//! - Async template discovery
//! - Async caching and hot-reload

use crate::context::TemplateContext;
use crate::error::{Result, TemplateError};
use crate::renderer::{OutputFormat, TemplateRenderer};
use serde_json::Value;
use std::collections::HashMap;
use std::path::{Path, PathBuf};

/// Async template renderer for async applications
///
/// Provides async versions of all template rendering operations
pub struct AsyncTemplateRenderer {
    /// Base template renderer
    renderer: TemplateRenderer,
}

impl AsyncTemplateRenderer {
    /// Create new async template renderer
    pub async fn new() -> Result<Self> {
        let renderer = TemplateRenderer::new()?;
        Ok(Self { renderer })
    }

    /// Create renderer with default context
    pub async fn with_defaults() -> Result<Self> {
        let renderer = TemplateRenderer::with_defaults()?;
        Ok(Self { renderer })
    }

    /// Set template context
    pub fn with_context(mut self, context: TemplateContext) -> Self {
        self.renderer = self.renderer.with_context(context);
        self
    }

    /// Render template string asynchronously
    ///
    /// # Arguments
    /// * `template` - Template content
    /// * `name` - Template name for error reporting
    pub async fn render_str(&mut self, template: &str, name: &str) -> Result<String> {
        // Template rendering is CPU-bound, so we run it in a blocking task
        // Clone strings to move into spawn_blocking
        let template = template.to_string();
        let name = name.to_string();
        let mut renderer = self.renderer.clone();
        tokio::task::spawn_blocking(move || renderer.render_str(&template, &name))
            .await
            .map_err(|e| TemplateError::InternalError(format!("Async rendering failed: {}", e)))?
    }

    /// Render template to specific format
    ///
    /// # Arguments
    /// * `template` - Template content
    /// * `name` - Template name
    /// * `format` - Output format
    pub async fn render_to_format(
        &mut self,
        template: &str,
        name: &str,
        format: OutputFormat,
    ) -> Result<String> {
        let rendered = self.render_str(template, name).await?;

        match format {
            OutputFormat::Toml => Ok(rendered),
            OutputFormat::Json => crate::simple::convert_to_json(&rendered),
            OutputFormat::Yaml => crate::simple::convert_to_yaml(&rendered),
            OutputFormat::Plain => crate::simple::strip_template_syntax(&rendered),
        }
    }

    /// Render template file asynchronously
    ///
    /// # Arguments
    /// * `path` - Path to template file
    pub async fn render_file<P: AsRef<Path>>(&mut self, path: P) -> Result<String> {
        let path = path.as_ref().to_path_buf();
        tokio::task::spawn_blocking(move || {
            let mut renderer = TemplateRenderer::new()?;
            renderer.render_file(&path)
        })
        .await
        .map_err(|e| TemplateError::InternalError(format!("Async file rendering failed: {}", e)))?
    }

    /// Merge user variables into context
    pub fn merge_user_vars(&mut self, user_vars: HashMap<String, Value>) {
        self.renderer.merge_user_vars(user_vars);
    }

    /// Access the underlying renderer
    pub fn renderer(&self) -> &TemplateRenderer {
        &self.renderer
    }

    /// Access the underlying renderer mutably
    pub fn renderer_mut(&mut self) -> &mut TemplateRenderer {
        &mut self.renderer
    }
}

/// Async convenience functions for simple template rendering
///
/// Render template string asynchronously
///
/// # Arguments
/// * `template` - Template content
/// * `vars` - Variables as key-value pairs
pub async fn async_render(template: &str, vars: HashMap<&str, &str>) -> Result<String> {
    let mut json_vars = HashMap::new();
    for (key, value) in vars {
        json_vars.insert(key.to_string(), Value::String(value.to_string()));
    }

    let mut renderer = AsyncTemplateRenderer::new().await?;
    renderer.merge_user_vars(json_vars);
    renderer.render_str(template, "async_template").await
}

/// Render template file asynchronously
///
/// # Arguments
/// * `path` - Path to template file
/// * `vars` - Variables as key-value pairs
pub async fn async_render_file<P: AsRef<Path>>(
    path: P,
    vars: HashMap<&str, &str>,
) -> Result<String> {
    let mut json_vars = HashMap::new();
    for (key, value) in vars {
        json_vars.insert(key.to_string(), Value::String(value.to_string()));
    }

    let mut renderer = AsyncTemplateRenderer::new().await?;
    renderer.merge_user_vars(json_vars);
    renderer.render_file(path).await
}

/// Render template with JSON variables asynchronously
pub async fn async_render_with_json(template: &str, vars: HashMap<&str, Value>) -> Result<String> {
    let mut json_vars = HashMap::new();
    for (key, value) in vars {
        json_vars.insert(key.to_string(), value);
    }

    let mut renderer = AsyncTemplateRenderer::new().await?;
    renderer.merge_user_vars(json_vars);
    renderer.render_str(template, "async_template").await
}

/// Async template builder for fluent configuration
///
/// Provides async versions of the template builder API
pub struct AsyncTemplateBuilder {
    template: Option<String>,
    variables: HashMap<String, Value>,
    format: OutputFormat,
    context: Option<TemplateContext>,
}

impl Default for AsyncTemplateBuilder {
    fn default() -> Self {
        Self {
            template: None,
            variables: HashMap::new(),
            format: OutputFormat::Toml,
            context: None,
        }
    }
}

impl AsyncTemplateBuilder {
    /// Create new async template builder
    pub fn new() -> Self {
        Self::default()
    }

    /// Set template content
    pub fn template<S: Into<String>>(mut self, template: S) -> Self {
        self.template = Some(template.into());
        self
    }

    /// Add string variable
    pub fn variable<K: Into<String>, V: Into<String>>(mut self, key: K, value: V) -> Self {
        self.variables
            .insert(key.into(), Value::String(value.into()));
        self
    }

    /// Add JSON variable
    pub fn json_variable<K: Into<String>>(mut self, key: K, value: Value) -> Self {
        self.variables.insert(key.into(), value);
        self
    }

    /// Set output format
    pub fn format(mut self, format: OutputFormat) -> Self {
        self.format = format;
        self
    }

    /// Set custom context
    pub fn context(mut self, context: TemplateContext) -> Self {
        self.context = Some(context);
        self
    }

    /// Render template asynchronously
    pub async fn render(self) -> Result<String> {
        let template = self
            .template
            .ok_or_else(|| TemplateError::ValidationError("No template provided".to_string()))?;

        if let Some(context) = self.context {
            let mut renderer = AsyncTemplateRenderer::new().await?.with_context(context);
            let result = renderer.render_str(&template, "async_template").await?;

            match self.format {
                OutputFormat::Toml => Ok(result),
                OutputFormat::Json => crate::simple::convert_to_json(&result),
                OutputFormat::Yaml => crate::simple::convert_to_yaml(&result),
                OutputFormat::Plain => crate::simple::strip_template_syntax(&result),
            }
        } else {
            let mut json_vars = HashMap::new();
            for (key, value) in self.variables {
                json_vars.insert(key, value);
            }

            let mut renderer = AsyncTemplateRenderer::new().await?;
            renderer.merge_user_vars(json_vars);
            let result = renderer.render_str(&template, "async_template").await?;

            match self.format {
                OutputFormat::Toml => Ok(result),
                OutputFormat::Json => crate::simple::convert_to_json(&result),
                OutputFormat::Yaml => crate::simple::convert_to_yaml(&result),
                OutputFormat::Plain => crate::simple::strip_template_syntax(&result),
            }
        }
    }
}

/// Async TOML file operations for async applications
pub mod async_toml {
    use super::*;
    use crate::toml::{TomlFile, TomlLoader, TomlWriter};
    use std::collections::HashMap;

    /// Load TOML file asynchronously
    ///
    /// # Arguments
    /// * `path` - Path to TOML file
    pub async fn load_toml_file<P: AsRef<Path>>(path: P) -> Result<TomlFile> {
        let path = path.as_ref().to_path_buf();
        tokio::task::spawn_blocking(move || {
            let loader = TomlLoader::new();
            loader.load_file(path)
        })
        .await
        .map_err(|e| TemplateError::InternalError(format!("Async TOML loading failed: {}", e)))?
    }

    /// Load all TOML files from directory asynchronously
    ///
    /// # Arguments
    /// * `search_paths` - Directories to search
    pub async fn load_all_toml_files(
        search_paths: Vec<&Path>,
    ) -> Result<HashMap<PathBuf, TomlFile>> {
        let paths: Vec<PathBuf> = search_paths.iter().map(|p| p.to_path_buf()).collect();
        tokio::task::spawn_blocking(move || {
            let loader = TomlLoader::new().with_search_paths(paths);
            loader.load_all()
        })
        .await
        .map_err(|e| {
            TemplateError::InternalError(format!("Async TOML directory loading failed: {}", e))
        })?
    }

    /// Write TOML file asynchronously
    ///
    /// # Arguments
    /// * `path` - Target file path
    /// * `content` - TOML content to write
    /// * `validator` - Optional validator
    pub async fn write_toml_file<P: AsRef<Path>>(
        path: P,
        content: &str,
        validator: Option<&crate::validation::TemplateValidator>,
    ) -> Result<()> {
        let path = path.as_ref().to_path_buf();
        let content = content.to_string();
        let validator = validator.cloned();

        tokio::task::spawn_blocking(move || {
            let writer = TomlWriter::new();
            writer.write_file(path, &content, validator.as_ref())
        })
        .await
        .map_err(|e| TemplateError::InternalError(format!("Async TOML writing failed: {}", e)))?
    }
}

/// Async template discovery for large codebases
pub mod async_discovery {
    use super::*;
    use crate::discovery::{TemplateDiscovery, TemplateLoader};

    /// Discover templates asynchronously
    ///
    /// # Arguments
    /// * `search_paths` - Directories to search
    /// * `patterns` - Glob patterns to match
    pub async fn discover_templates(
        search_paths: Vec<&Path>,
        patterns: Vec<&str>,
    ) -> Result<TemplateLoader> {
        let paths: Vec<PathBuf> = search_paths.iter().map(|p| p.to_path_buf()).collect();
        let patterns: Vec<String> = patterns.iter().map(|s| s.to_string()).collect();

        tokio::task::spawn_blocking(move || {
            let mut discovery = TemplateDiscovery::new();
            for path in paths {
                discovery = discovery.with_search_path(path);
            }
            for pattern in patterns {
                discovery = discovery.with_glob_pattern(&pattern);
            }
            discovery.load()
        })
        .await
        .map_err(|e| {
            TemplateError::InternalError(format!("Async template discovery failed: {}", e))
        })?
    }
}

/// Async template validation for large templates
pub mod async_validation {
    use super::*;

    /// Validate template output asynchronously
    ///
    /// # Arguments
    /// * `output` - Rendered template content
    /// * `template_name` - Template name for error reporting
    /// * `validator` - Template validator
    pub async fn validate_async(
        output: &str,
        template_name: &str,
        validator: &crate::validation::TemplateValidator,
    ) -> Result<()> {
        let output = output.to_string();
        let template_name = template_name.to_string();
        let validator = validator.clone();
        tokio::task::spawn_blocking(move || validator.validate(&output, &template_name))
            .await
            .map_err(|e| TemplateError::InternalError(format!("Async validation failed: {}", e)))?
    }
}

/// Async template caching for high-performance applications
pub mod async_cache {
    use super::*;
    use crate::cache::CachedRenderer;

    /// Create async cached renderer
    ///
    /// # Arguments
    /// * `context` - Template context
    /// * `hot_reload` - Enable hot-reload
    pub async fn create_async_cached_renderer(
        context: TemplateContext,
        hot_reload: bool,
    ) -> Result<CachedRenderer> {
        tokio::task::spawn_blocking(move || CachedRenderer::new(context, hot_reload))
            .await
            .map_err(|e| {
                TemplateError::InternalError(format!(
                    "Async cached renderer creation failed: {}",
                    e
                ))
            })?
    }
}

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

    #[tokio::test]
    async fn test_async_render() {
        let result = async_render(
            "Hello {{ name }}!",
            [("name", "World")].iter().cloned().collect(),
        )
        .await
        .unwrap();
        assert_eq!(result, "Hello World!");
    }

    #[tokio::test]
    async fn test_async_template_builder() {
        let result = AsyncTemplateBuilder::new()
            .template("Service: {{ service }}")
            .variable("service", "my-service")
            .render()
            .await
            .unwrap();

        assert_eq!(result, "Service: my-service");
    }

    #[tokio::test]
    async fn test_async_toml_loading() {
        use std::fs;
        use tempfile::tempdir;

        let temp_dir = tempdir().unwrap();
        let toml_file = temp_dir.path().join("test.toml");

        let content = r#"
[service]
name = "test-service"
        "#;

        fs::write(&toml_file, content).unwrap();

        let file = async_toml::load_toml_file(&toml_file).await.unwrap();
        assert_eq!(file.path, toml_file);
        assert!(file.parsed.get("service").is_some());
    }
}