ggen-core 26.7.2

Core graph-aware code generation 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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
//! Template context for variable resolution
//!
//! Provides context management for template variable substitution.
//!
//! ## Features
//!
//! - **Variable management**: Store and retrieve template variables
//! - **Tera integration**: Seamless integration with Tera template engine
//! - **Type-safe values**: Support for JSON values (strings, numbers, objects, arrays)
//! - **Context conversion**: Convert to Tera Context for rendering
//!
//! ## Examples
//!
//! ### Creating and Using Template Context
//!
//! ```rust
//! use crate::templates::context::TemplateContext;
//! use serde_json::json;
//!
//! let mut ctx = TemplateContext::new();
//!
//! // Add variables
//! ctx.set("name", json!("MyApp")).unwrap();
//! ctx.set("version", json!("1.0.0")).unwrap();
//! ctx.set("author", json!("Alice")).unwrap();
//!
//! // Verify variables are set
//! assert_eq!(ctx.get_string("name"), Some("MyApp".to_string()));
//! ```
//!
//! ### Working with Nested Values
//!
//! ```rust
//! use crate::templates::context::TemplateContext;
//! use serde_json::json;
//!
//! let mut ctx = TemplateContext::new();
//!
//! // Add nested object
//! ctx.set("project", json!({
//!     "name": "MyApp",
//!     "version": "1.0.0",
//!     "dependencies": ["serde", "tokio"]
//! })).unwrap();
//!
//! // Verify nested value can be accessed
//! let project = ctx.get("project").unwrap();
//! assert!(project.is_object());
//! ```

use crate::utils::error::{Error, Result};
use serde_json::Value;
use std::collections::BTreeMap;
use tera::Context;

/// Template context for variable resolution
///
/// Manages template variables and provides integration with the Tera template engine.
/// Supports JSON values (strings, numbers, objects, arrays) for flexible variable types.
///
/// # Examples
///
/// ```rust
/// use crate::templates::context::TemplateContext;
/// use serde_json::json;
///
/// let mut ctx = TemplateContext::new();
/// ctx.set("name", json!("MyApp")).unwrap();
/// ctx.set("version", json!("1.0.0")).unwrap();
///
/// assert_eq!(ctx.get_string("name"), Some("MyApp".to_string()));
/// ```
#[derive(Debug, Clone)]
pub struct TemplateContext {
    /// Variables for template rendering
    variables: BTreeMap<String, Value>,
}

impl TemplateContext {
    /// Create a new empty template context
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::templates::context::TemplateContext;
    ///
    /// let ctx = TemplateContext::new();
    /// assert!(ctx.variable_names().is_empty());
    /// ```
    pub fn new() -> Self {
        Self {
            variables: BTreeMap::new(),
        }
    }

    /// Create from a map of string variables
    ///
    /// Converts a map of string key-value pairs into a template context.
    /// All values are stored as JSON strings.
    ///
    /// # Arguments
    ///
    /// * `variables` - Map of variable names to string values
    ///
    /// # Returns
    ///
    /// A new `TemplateContext` with the provided variables.
    ///
    /// # Errors
    ///
    /// Returns an error if the variable name is invalid or the value cannot be stored.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::templates::context::TemplateContext;
    /// use std::collections::BTreeMap;
    ///
    /// # fn main() -> crate::utils::error::Result<()> {
    /// let mut vars = BTreeMap::new();
    /// vars.insert("service_name".to_string(), "my-service".to_string());
    /// vars.insert("port".to_string(), "8080".to_string());
    ///
    /// let ctx = TemplateContext::from_map(vars)?;
    /// assert_eq!(ctx.get_string("service_name"), Some("my-service".to_string()));
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_map(variables: BTreeMap<String, String>) -> Result<Self> {
        let mut ctx = Self::new();
        for (key, value) in variables {
            ctx.set(key, value)?;
        }
        Ok(ctx)
    }

    /// Set a variable in the context
    ///
    /// Sets or updates a variable value. The value can be any JSON-compatible type
    /// (string, number, boolean, object, array, or null).
    ///
    /// # Arguments
    ///
    /// * `key` - Variable name (any type that can be converted to `String`)
    /// * `value` - Variable value (any type that can be converted to `serde_json::Value`)
    ///
    /// # Returns
    ///
    /// `Ok(())` on success.
    ///
    /// # Errors
    ///
    /// Returns an error if the variable name is invalid or the value cannot be stored.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::templates::context::TemplateContext;
    /// use serde_json::json;
    ///
    /// # fn main() -> crate::utils::error::Result<()> {
    /// let mut ctx = TemplateContext::new();
    ///
    /// // Set string value
    /// ctx.set("name", json!("MyApp"))?;
    ///
    /// // Set number value
    /// ctx.set("port", json!(8080))?;
    ///
    /// // Set nested object
    /// ctx.set("project", json!({
    ///     "name": "MyApp",
    ///     "version": "1.0.0"
    /// }))?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn set<K: Into<String>, V: Into<Value>>(&mut self, key: K, value: V) -> Result<()> {
        self.variables.insert(key.into(), value.into());
        Ok(())
    }

    /// Get a variable from the context
    ///
    /// Returns a reference to the variable value if it exists.
    ///
    /// # Arguments
    ///
    /// * `key` - Variable name to look up
    ///
    /// # Returns
    ///
    /// `Some(&Value)` if the variable exists, `None` otherwise.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::templates::context::TemplateContext;
    /// use serde_json::json;
    ///
    /// # fn main() -> crate::utils::error::Result<()> {
    /// let mut ctx = TemplateContext::new();
    /// ctx.set("name", json!("MyApp"))?;
    ///
    /// let value = ctx.get("name");
    /// assert!(value.is_some());
    /// assert_eq!(value.unwrap().as_str(), Some("MyApp"));
    ///
    /// let missing = ctx.get("nonexistent");
    /// assert!(missing.is_none());
    /// # Ok(())
    /// # }
    /// ```
    pub fn get(&self, key: &str) -> Option<&Value> {
        self.variables.get(key)
    }

    /// Get a variable as a string
    ///
    /// Returns the variable value as a string if it exists and is a string type.
    ///
    /// # Arguments
    ///
    /// * `key` - Variable name to look up
    ///
    /// # Returns
    ///
    /// `Some(String)` if the variable exists and is a string, `None` otherwise.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::templates::context::TemplateContext;
    /// use serde_json::json;
    ///
    /// # fn main() -> crate::utils::error::Result<()> {
    /// let mut ctx = TemplateContext::new();
    /// ctx.set("name", json!("MyApp"))?;
    ///
    /// assert_eq!(ctx.get_string("name"), Some("MyApp".to_string()));
    ///
    /// // Number values return None
    /// ctx.set("port", json!(8080))?;
    /// assert_eq!(ctx.get_string("port"), None);
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_string(&self, key: &str) -> Option<String> {
        self.variables
            .get(key)
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
    }

    /// Check if a variable exists
    ///
    /// Returns `true` if the variable exists in the context, regardless of its value type.
    ///
    /// # Arguments
    ///
    /// * `key` - Variable name to check
    ///
    /// # Returns
    ///
    /// `true` if the variable exists, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::templates::context::TemplateContext;
    /// use serde_json::json;
    ///
    /// # fn main() -> crate::utils::error::Result<()> {
    /// let mut ctx = TemplateContext::new();
    /// ctx.set("name", json!("MyApp"))?;
    ///
    /// assert!(ctx.contains("name"));
    /// assert!(!ctx.contains("nonexistent"));
    /// # Ok(())
    /// # }
    /// ```
    pub fn contains(&self, key: &str) -> bool {
        self.variables.contains_key(key)
    }

    /// Merge another context into this one
    ///
    /// Adds all variables from `other` into this context. If a variable exists
    /// in both contexts, the value from `other` will overwrite the existing value.
    ///
    /// # Arguments
    ///
    /// * `other` - The context to merge into this one
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::templates::context::TemplateContext;
    /// use serde_json::json;
    ///
    /// # fn main() -> crate::utils::error::Result<()> {
    /// let mut ctx1 = TemplateContext::new();
    /// ctx1.set("name", json!("App1"))?;
    ///
    /// let mut ctx2 = TemplateContext::new();
    /// ctx2.set("port", json!("8080"))?;
    /// ctx2.set("name", json!("App2"))?; // Will overwrite ctx1's "name"
    ///
    /// ctx1.merge(&ctx2);
    ///
    /// assert_eq!(ctx1.get_string("name"), Some("App2".to_string()));
    /// assert_eq!(ctx1.get_string("port"), Some("8080".to_string()));
    /// # Ok(())
    /// # }
    /// ```
    pub fn merge(&mut self, other: &TemplateContext) {
        for (key, value) in &other.variables {
            self.variables.insert(key.clone(), value.clone());
        }
    }

    /// Convert to Tera Context
    ///
    /// Converts this template context into a Tera `Context` for use with
    /// the Tera template engine. All variable types are preserved.
    ///
    /// # Returns
    ///
    /// A Tera `Context` containing all variables from this context.
    ///
    /// # Errors
    ///
    /// Returns an error if the variable name is invalid or the value cannot be stored.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::templates::context::TemplateContext;
    /// use serde_json::json;
    ///
    /// # fn main() -> crate::utils::error::Result<()> {
    /// let mut ctx = TemplateContext::new();
    /// ctx.set("name", json!("MyApp"))?;
    /// ctx.set("port", json!(8080))?;
    ///
    /// let tera_ctx = ctx.to_tera_context()?;
    /// // tera_ctx can now be used with Tera templates
    /// # Ok(())
    /// # }
    /// ```
    pub fn to_tera_context(&self) -> Result<Context> {
        let mut context = Context::new();

        for (key, value) in &self.variables {
            match value {
                Value::String(s) => context.insert(key, s),
                Value::Number(n) => context.insert(key, n),
                Value::Bool(b) => context.insert(key, b),
                Value::Array(arr) => context.insert(key, arr),
                Value::Object(obj) => context.insert(key, obj),
                Value::Null => context.insert(key, &Option::<String>::None),
            }
        }

        Ok(context)
    }

    /// Get all variable names
    ///
    /// Returns a vector of all variable names in the context, in sorted order.
    ///
    /// # Returns
    ///
    /// A vector of variable name string slices.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::templates::context::TemplateContext;
    /// use serde_json::json;
    ///
    /// # fn main() -> crate::utils::error::Result<()> {
    /// let mut ctx = TemplateContext::new();
    /// ctx.set("name", json!("MyApp"))?;
    /// ctx.set("port", json!(8080))?;
    /// ctx.set("version", json!("1.0.0"))?;
    ///
    /// let names = ctx.variable_names();
    /// assert_eq!(names.len(), 3);
    /// assert!(names.contains(&"name"));
    /// assert!(names.contains(&"port"));
    /// assert!(names.contains(&"version"));
    /// # Ok(())
    /// # }
    /// ```
    pub fn variable_names(&self) -> Vec<&str> {
        self.variables.keys().map(|s| s.as_str()).collect()
    }

    /// Validate that all required variables are present
    ///
    /// Checks that all variables in the `required` list exist in this context.
    /// Returns an error if any required variables are missing.
    ///
    /// # Arguments
    ///
    /// * `required` - Slice of variable names that must be present
    ///
    /// # Returns
    ///
    /// `Ok(())` if all required variables are present.
    ///
    /// # Errors
    ///
    /// Returns an error if any required variables are missing, with a message
    /// listing all missing variables.
    ///
    /// # Examples
    ///
    /// ## Success case
    ///
    /// ```rust
    /// use crate::templates::context::TemplateContext;
    /// use serde_json::json;
    ///
    /// # fn main() -> crate::utils::error::Result<()> {
    /// let mut ctx = TemplateContext::new();
    /// ctx.set("name", json!("MyApp"))?;
    /// ctx.set("port", json!(8080))?;
    ///
    /// let required = vec!["name".to_string(), "port".to_string()];
    /// ctx.validate_required(&required)?; // Ok
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ## Error case
    ///
    /// ```rust
    /// use crate::templates::context::TemplateContext;
    /// use serde_json::json;
    ///
    /// # fn main() -> crate::utils::error::Result<()> {
    /// let mut ctx = TemplateContext::new();
    /// ctx.set("name", json!("MyApp"))?;
    ///
    /// let required = vec!["name".to_string(), "port".to_string()];
    /// let result = ctx.validate_required(&required);
    /// assert!(result.is_err());
    /// assert!(result.unwrap_err().to_string().contains("port"));
    /// # Ok(())
    /// # }
    /// ```
    pub fn validate_required(&self, required: &[String]) -> Result<()> {
        let missing: Vec<_> = required
            .iter()
            .filter(|var| !self.variables.contains_key(*var))
            .collect();

        if !missing.is_empty() {
            return Err(crate::utils::error::Error::new(&format!(
                "Missing required template variables: {}",
                missing
                    .iter()
                    .map(|v| v.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            )));
        }

        Ok(())
    }

    /// Apply defaults for missing variables
    ///
    /// Sets default values for variables that don't exist in the context.
    /// Existing variables are not overwritten.
    ///
    /// # Arguments
    ///
    /// * `defaults` - Map of variable names to default string values
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::templates::context::TemplateContext;
    /// use serde_json::json;
    /// use std::collections::BTreeMap;
    ///
    /// # fn main() -> crate::utils::error::Result<()> {
    /// let mut ctx = TemplateContext::new();
    /// ctx.set("name", json!("MyApp"))?; // Existing value
    ///
    /// let mut defaults = BTreeMap::new();
    /// defaults.insert("name".to_string(), "DefaultApp".to_string()); // Won't overwrite
    /// defaults.insert("port".to_string(), "8080".to_string()); // Will be applied
    ///
    /// ctx.apply_defaults(&defaults);
    ///
    /// // Existing value preserved
    /// assert_eq!(ctx.get_string("name"), Some("MyApp".to_string()));
    /// // Default applied
    /// assert_eq!(ctx.get_string("port"), Some("8080".to_string()));
    /// # Ok(())
    /// # }
    /// ```
    pub fn apply_defaults(&mut self, defaults: &BTreeMap<String, String>) {
        for (key, value) in defaults {
            if !self.variables.contains_key(key) {
                self.variables
                    .insert(key.clone(), Value::String(value.clone()));
            }
        }
    }

    /// Render a template string with this context
    ///
    /// Renders a Tera template string using the variables in this context.
    /// The template string can contain Tera syntax like `{{ variable }}`.
    ///
    /// # Arguments
    ///
    /// * `template` - Tera template string to render
    ///
    /// # Returns
    ///
    /// The rendered string with variables substituted.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Template syntax is invalid
    /// - Required variables are missing
    /// - Template rendering fails
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::templates::context::TemplateContext;
    /// use serde_json::json;
    ///
    /// # fn main() -> crate::utils::error::Result<()> {
    /// let mut ctx = TemplateContext::new();
    /// ctx.set("name", json!("World"))?;
    /// ctx.set("count", json!(42))?;
    ///
    /// let rendered = ctx.render_string("Hello, {{ name }}! Count: {{ count }}")?;
    /// assert_eq!(rendered, "Hello, World! Count: 42");
    /// # Ok(())
    /// # }
    /// ```
    pub fn render_string(&self, template: &str) -> Result<String> {
        let mut tera = tera::Tera::default();
        let context = self.to_tera_context()?;

        tera.render_str(template, &context)
            .map_err(|e| Error::with_context("Failed to render template string", &e.to_string()))
    }

    /// Clone the variables map
    pub fn variables(&self) -> &BTreeMap<String, Value> {
        &self.variables
    }
}

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

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

    #[test]
    fn test_new_context() {
        let ctx = TemplateContext::new();
        assert!(ctx.variables.is_empty());
    }

    #[test]
    fn test_set_and_get() {
        let mut ctx = TemplateContext::new();
        ctx.set("name", "test").unwrap();

        assert_eq!(ctx.get_string("name"), Some("test".to_string()));
        assert!(ctx.contains("name"));
    }

    #[test]
    fn test_from_map() {
        let mut vars = BTreeMap::new();
        vars.insert("service_name".to_string(), "my-service".to_string());
        vars.insert("port".to_string(), "8080".to_string());

        let ctx = TemplateContext::from_map(vars).unwrap();

        assert_eq!(
            ctx.get_string("service_name"),
            Some("my-service".to_string())
        );
        assert_eq!(ctx.get_string("port"), Some("8080".to_string()));
    }

    #[test]
    fn test_merge() {
        let mut ctx1 = TemplateContext::new();
        ctx1.set("name", "test1").unwrap();

        let mut ctx2 = TemplateContext::new();
        ctx2.set("port", "8080").unwrap();

        ctx1.merge(&ctx2);

        assert_eq!(ctx1.get_string("name"), Some("test1".to_string()));
        assert_eq!(ctx1.get_string("port"), Some("8080".to_string()));
    }

    #[test]
    fn test_validate_required() {
        let mut ctx = TemplateContext::new();
        ctx.set("name", "test").unwrap();

        let required = vec!["name".to_string(), "port".to_string()];
        let result = ctx.validate_required(&required);

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("port"));
    }

    #[test]
    fn test_apply_defaults() {
        let mut ctx = TemplateContext::new();
        ctx.set("name", "test").unwrap();

        let mut defaults = BTreeMap::new();
        defaults.insert("name".to_string(), "default-name".to_string());
        defaults.insert("port".to_string(), "8080".to_string());

        ctx.apply_defaults(&defaults);

        // Existing value should not be overwritten
        assert_eq!(ctx.get_string("name"), Some("test".to_string()));
        // Default should be applied for missing value
        assert_eq!(ctx.get_string("port"), Some("8080".to_string()));
    }

    #[test]
    fn test_render_string() {
        let mut ctx = TemplateContext::new();
        ctx.set("name", "World").unwrap();
        ctx.set("count", 42).unwrap();

        let rendered = ctx
            .render_string("Hello, {{ name }}! Count: {{ count }}")
            .unwrap();
        assert_eq!(rendered, "Hello, World! Count: 42");
    }

    #[test]
    fn test_variable_names() {
        let mut ctx = TemplateContext::new();
        ctx.set("name", "test").unwrap();
        ctx.set("port", "8080").unwrap();

        let names = ctx.variable_names();
        assert_eq!(names.len(), 2);
        assert!(names.contains(&"name"));
        assert!(names.contains(&"port"));
    }
}