ggen-core 26.7.3

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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
//! Template format definitions
//!
//! Defines the structure and parsing of file tree templates.
//!
//! ## Features
//!
//! - **File tree representation**: Hierarchical structure for directory and file nodes
//! - **Template format parsing**: Parse YAML/JSON template definitions
//! - **Node types**: Support for directories and files
//! - **Metadata support**: Attach metadata to nodes
//!
//! ## Examples
//!
//! ### Creating a File Tree Template
//!
//! ```rust,no_run
//! use crate::templates::format::{FileTreeNode, TemplateFormat};
//!
//! # fn main() -> crate::utils::error::Result<()> {
//! let mut template = TemplateFormat::new("my-template");
//!
//! let mut src = FileTreeNode::directory("src");
//! src.children.push(FileTreeNode::file_with_content(
//!     "main.rs",
//!     "fn main() { println!(\"Hello\"); }",
//! ));
//! template.add_node(src);
//!
//! assert_eq!(template.name, "my-template");
//! # Ok(())
//! # }
//! ```
//!
//! ### Parsing Template Format
//!
//! ```rust,no_run
//! use crate::templates::format::TemplateFormat;
//!
//! # fn main() -> crate::utils::error::Result<()> {
//! let yaml = r#"
//! nodes:
//!   - name: src
//!     type: directory
//!     children:
//!       - name: main.rs
//!         type: file
//!         content: "fn main() {}"
//! "#;
//!
//! let template: TemplateFormat = serde_yaml::from_str(yaml)?;
//! # Ok(())
//! # }
//! ```

use crate::utils::error::{Error, Result};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

/// Node type in the file tree template
///
/// Represents whether a node in the file tree is a directory or a file.
///
/// # Examples
///
/// ```rust
/// use crate::templates::format::NodeType;
///
/// let dir_type = NodeType::Directory;
/// let file_type = NodeType::File;
///
/// assert_ne!(dir_type, file_type);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NodeType {
    /// Directory node - can contain child nodes
    Directory,
    /// File node - contains content or references a template
    File,
}

/// A node in the file tree template
///
/// Represents either a file or directory in the generated file tree.
/// Directory nodes can contain children, while file nodes contain content
/// or reference template files.
///
/// # Examples
///
/// ## Creating a directory node
///
/// ```rust
/// use crate::templates::format::FileTreeNode;
///
/// let dir = FileTreeNode::directory("src");
/// assert_eq!(dir.name, "src");
/// ```
///
/// ## Creating a file node with content
///
/// ```rust
/// use crate::templates::format::FileTreeNode;
///
/// let file = FileTreeNode::file_with_content("main.rs", "fn main() {}");
/// assert_eq!(file.name, "main.rs");
/// assert_eq!(file.content, Some("fn main() {}".to_string()));
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileTreeNode {
    /// Type of node (file or directory)
    #[serde(rename = "type")]
    pub node_type: NodeType,

    /// Name of the file or directory (may contain template variables)
    pub name: String,

    /// Children nodes (for directories)
    #[serde(default)]
    pub children: Vec<FileTreeNode>,

    /// Inline content (for files)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,

    /// Template file reference (for files)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub template: Option<String>,

    /// File permissions (Unix mode)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mode: Option<u32>,
}

/// Template format with metadata and RDF support
///
/// Represents a complete file tree template with metadata, variables, defaults,
/// and RDF annotations. This is the top-level structure for file tree templates.
///
/// # Examples
///
/// ```rust
/// use crate::templates::format::{TemplateFormat, FileTreeNode};
///
/// let mut format = TemplateFormat::new("my-template");
/// format.add_variable("service_name");
/// format.add_default("port", "8080");
/// format.add_node(FileTreeNode::directory("src"));
///
/// assert_eq!(format.name, "my-template");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemplateFormat {
    /// Template name
    pub name: String,

    /// Template description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// RDF metadata
    #[serde(default)]
    pub rdf: BTreeMap<String, serde_yaml::Value>,

    /// Required variables
    #[serde(default)]
    pub variables: Vec<String>,

    /// Default variable values
    #[serde(default)]
    pub defaults: BTreeMap<String, String>,

    /// Root nodes of the file tree
    pub tree: Vec<FileTreeNode>,
}

impl TemplateFormat {
    /// Create a new template format
    ///
    /// Creates an empty template format with the given name. Variables, defaults,
    /// and nodes can be added using builder methods.
    ///
    /// # Arguments
    ///
    /// * `name` - Template name (must be non-empty)
    ///
    /// # Returns
    ///
    /// A new `TemplateFormat` with empty variables, defaults, and tree.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::templates::format::TemplateFormat;
    ///
    /// let format = TemplateFormat::new("my-template");
    /// assert_eq!(format.name, "my-template");
    /// assert!(format.variables.is_empty());
    /// assert!(format.tree.is_empty());
    /// ```
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: None,
            rdf: BTreeMap::new(),
            variables: Vec::new(),
            defaults: BTreeMap::new(),
            tree: Vec::new(),
        }
    }

    /// Add a variable to the template
    ///
    /// Adds a required variable to the template. Variables must be provided
    /// when generating from this template (unless they have defaults).
    /// Returns `&mut Self` for method chaining.
    ///
    /// # Arguments
    ///
    /// * `var` - Variable name to add
    ///
    /// # Returns
    ///
    /// `&mut Self` for method chaining.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::templates::format::TemplateFormat;
    ///
    /// let mut format = TemplateFormat::new("my-template");
    /// format.add_variable("service_name")
    ///       .add_variable("port");
    ///
    /// assert_eq!(format.variables.len(), 2);
    /// assert!(format.variables.contains(&"service_name".to_string()));
    /// ```
    pub fn add_variable(&mut self, var: impl Into<String>) -> &mut Self {
        self.variables.push(var.into());
        self
    }

    /// Add a default value for a variable
    ///
    /// Sets a default value for a variable. Defaults are only applied if the
    /// variable is not provided during generation. Returns `&mut Self` for method chaining.
    ///
    /// # Arguments
    ///
    /// * `key` - Variable name
    /// * `value` - Default value (as string)
    ///
    /// # Returns
    ///
    /// `&mut Self` for method chaining.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::templates::format::TemplateFormat;
    ///
    /// let mut format = TemplateFormat::new("my-template");
    /// format.add_variable("port")
    ///       .add_default("port", "8080");
    ///
    /// assert_eq!(format.defaults.get("port"), Some(&"8080".to_string()));
    /// ```
    pub fn add_default(&mut self, key: impl Into<String>, value: impl Into<String>) -> &mut Self {
        self.defaults.insert(key.into(), value.into());
        self
    }

    /// Add a tree node
    ///
    /// Adds a root-level node to the file tree. Returns `&mut Self` for method chaining.
    ///
    /// # Arguments
    ///
    /// * `node` - File tree node to add
    ///
    /// # Returns
    ///
    /// `&mut Self` for method chaining.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::templates::format::{TemplateFormat, FileTreeNode};
    ///
    /// let mut format = TemplateFormat::new("my-template");
    /// format.add_node(FileTreeNode::directory("src"))
    ///       .add_node(FileTreeNode::directory("tests"));
    ///
    /// assert_eq!(format.tree.len(), 2);
    /// ```
    pub fn add_node(&mut self, node: FileTreeNode) -> &mut Self {
        self.tree.push(node);
        self
    }

    /// Parse from YAML string
    ///
    /// Parses a template format from a YAML string. The YAML should match
    /// the `TemplateFormat` structure.
    ///
    /// # Arguments
    ///
    /// * `yaml` - YAML string to parse
    ///
    /// # Returns
    ///
    /// A parsed `TemplateFormat` on success.
    ///
    /// # Errors
    ///
    /// Returns an error if the YAML is invalid or doesn't match the expected structure.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::templates::format::TemplateFormat;
    ///
    /// # fn main() -> crate::utils::error::Result<()> {
    /// let yaml = r#"
    /// name: my-template
    /// variables:
    ///   - service_name
    /// tree:
    ///   - name: src
    ///     type: directory
    /// "#;
    ///
    /// let format = TemplateFormat::from_yaml(yaml)?;
    /// assert_eq!(format.name, "my-template");
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_yaml(yaml: &str) -> Result<Self> {
        serde_yaml::from_str(yaml).map_err(|e| {
            Error::with_context("Failed to parse template format from YAML", &e.to_string())
        })
    }

    /// Serialize to YAML string
    ///
    /// Converts this template format to a YAML string representation.
    ///
    /// # Returns
    ///
    /// YAML string representation of the template format.
    ///
    /// # Errors
    ///
    /// Returns an error if serialization fails.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::templates::format::{TemplateFormat, FileTreeNode};
    ///
    /// # fn main() -> crate::utils::error::Result<()> {
    /// let mut format = TemplateFormat::new("my-template");
    /// format.add_node(FileTreeNode::directory("src"));
    ///
    /// let yaml = format.to_yaml()?;
    /// assert!(yaml.contains("name: my-template"));
    /// # Ok(())
    /// # }
    /// ```
    pub fn to_yaml(&self) -> Result<String> {
        serde_yaml::to_string(self).map_err(|e| {
            Error::with_context(
                "Failed to serialize template format to YAML",
                &e.to_string(),
            )
        })
    }

    /// Validate the template format
    ///
    /// Validates that the template format is well-formed:
    /// - Name is not empty
    /// - Tree contains at least one node
    /// - All nodes are valid (file nodes have content/template, directories don't)
    ///
    /// # Returns
    ///
    /// `Ok(())` if the template is valid.
    ///
    /// # Errors
    ///
    /// Returns an error if validation fails, with a message describing the issue.
    ///
    /// # Examples
    ///
    /// ## Success case
    ///
    /// ```rust
    /// use crate::templates::format::{TemplateFormat, FileTreeNode};
    ///
    /// # fn main() -> crate::utils::error::Result<()> {
    /// let mut format = TemplateFormat::new("my-template");
    /// format.add_node(FileTreeNode::directory("src"));
    ///
    /// format.validate()?; // Ok
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ## Error case - empty tree
    ///
    /// ```rust
    /// use crate::templates::format::TemplateFormat;
    ///
    /// let format = TemplateFormat::new("my-template");
    /// let result = format.validate();
    /// assert!(result.is_err());
    /// ```
    ///
    /// ## Error case - invalid file node
    ///
    /// ```rust
    /// use crate::templates::format::{TemplateFormat, FileTreeNode, NodeType};
    ///
    /// let mut format = TemplateFormat::new("my-template");
    /// let mut invalid_file = FileTreeNode {
    ///     node_type: NodeType::File,
    ///     name: "test.rs".to_string(),
    ///     children: vec![],
    ///     content: None,
    ///     template: None,
    ///     mode: None,
    /// };
    /// format.add_node(invalid_file);
    ///
    /// let result = format.validate();
    /// assert!(result.is_err());
    /// ```
    pub fn validate(&self) -> Result<()> {
        if self.name.is_empty() {
            return Err(crate::utils::error::Error::new(
                "Template name cannot be empty",
            ));
        }

        if self.tree.is_empty() {
            return Err(crate::utils::error::Error::new(
                "Template must contain at least one tree node",
            ));
        }

        Self::validate_nodes(&self.tree)?;

        Ok(())
    }

    fn validate_nodes(nodes: &[FileTreeNode]) -> Result<()> {
        for node in nodes {
            if node.name.is_empty() {
                return Err(crate::utils::error::Error::new("Node name cannot be empty"));
            }

            match node.node_type {
                NodeType::File => {
                    if node.content.is_none() && node.template.is_none() {
                        return Err(crate::utils::error::Error::new(&format!(
                            "File node '{}' must have either content or template",
                            node.name
                        )));
                    }
                    if !node.children.is_empty() {
                        return Err(crate::utils::error::Error::new(&format!(
                            "File node '{}' cannot have children",
                            node.name
                        )));
                    }
                }
                NodeType::Directory => {
                    if node.content.is_some() || node.template.is_some() {
                        return Err(crate::utils::error::Error::new(&format!(
                            "Directory node '{}' cannot have content or template",
                            node.name
                        )));
                    }
                    Self::validate_nodes(&node.children)?;
                }
            }
        }
        Ok(())
    }
}

impl FileTreeNode {
    /// Create a new directory node
    ///
    /// Creates a directory node with no children. Children can be added
    /// using `add_child()`.
    ///
    /// # Arguments
    ///
    /// * `name` - Directory name (may contain template variables like `{{ name }}`)
    ///
    /// # Returns
    ///
    /// A new `FileTreeNode` with `NodeType::Directory`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::templates::format::{FileTreeNode, NodeType};
    ///
    /// let dir = FileTreeNode::directory("src");
    /// assert_eq!(dir.node_type, NodeType::Directory);
    /// assert_eq!(dir.name, "src");
    /// assert!(dir.children.is_empty());
    /// ```
    pub fn directory(name: impl Into<String>) -> Self {
        Self {
            node_type: NodeType::Directory,
            name: name.into(),
            children: Vec::new(),
            content: None,
            template: None,
            mode: None,
        }
    }

    /// Create a new file node with inline content
    ///
    /// Creates a file node with inline content that will be written directly
    /// to the generated file. The content may contain template variables.
    ///
    /// # Arguments
    ///
    /// * `name` - File name (may contain template variables)
    /// * `content` - File content (may contain template variables)
    ///
    /// # Returns
    ///
    /// A new `FileTreeNode` with `NodeType::File` and inline content.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::templates::format::{FileTreeNode, NodeType};
    ///
    /// let file = FileTreeNode::file_with_content("main.rs", "fn main() {}");
    /// assert_eq!(file.node_type, NodeType::File);
    /// assert_eq!(file.name, "main.rs");
    /// assert_eq!(file.content, Some("fn main() {}".to_string()));
    /// ```
    pub fn file_with_content(name: impl Into<String>, content: impl Into<String>) -> Self {
        Self {
            node_type: NodeType::File,
            name: name.into(),
            children: Vec::new(),
            content: Some(content.into()),
            template: None,
            mode: None,
        }
    }

    /// Create a new file node with template reference
    ///
    /// Creates a file node that references an external template file.
    /// The template will be loaded and rendered during generation.
    ///
    /// # Arguments
    ///
    /// * `name` - File name (may contain template variables)
    /// * `template` - Path to template file (relative to template base directory)
    ///
    /// # Returns
    ///
    /// A new `FileTreeNode` with `NodeType::File` and a template reference.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::templates::format::{FileTreeNode, NodeType};
    ///
    /// let file = FileTreeNode::file_with_template("lib.rs", "templates/lib.rs.tera");
    /// assert_eq!(file.node_type, NodeType::File);
    /// assert_eq!(file.name, "lib.rs");
    /// assert_eq!(file.template, Some("templates/lib.rs.tera".to_string()));
    /// ```
    pub fn file_with_template(name: impl Into<String>, template: impl Into<String>) -> Self {
        Self {
            node_type: NodeType::File,
            name: name.into(),
            children: Vec::new(),
            content: None,
            template: Some(template.into()),
            mode: None,
        }
    }

    /// Add a child node (for directories)
    ///
    /// Adds a child node to this directory. Only valid for directory nodes.
    /// Returns `&mut Self` for method chaining.
    ///
    /// # Arguments
    ///
    /// * `child` - Child node to add
    ///
    /// # Returns
    ///
    /// `&mut Self` for method chaining.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::templates::format::FileTreeNode;
    ///
    /// let mut dir = FileTreeNode::directory("src");
    /// dir.add_child(FileTreeNode::file_with_content("main.rs", "fn main() {}"));
    ///
    /// assert_eq!(dir.children.len(), 1);
    /// assert_eq!(dir.children[0].name, "main.rs");
    /// ```
    pub fn add_child(&mut self, child: FileTreeNode) -> &mut Self {
        self.children.push(child);
        self
    }

    /// Set file permissions
    ///
    /// Sets Unix file permissions (mode) for this file node. Only valid for file nodes.
    /// Returns `Self` for method chaining.
    ///
    /// # Arguments
    ///
    /// * `mode` - Unix file mode (e.g., `0o755` for executable)
    ///
    /// # Returns
    ///
    /// `Self` for method chaining.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::templates::format::FileTreeNode;
    ///
    /// let file = FileTreeNode::file_with_content("script.sh", "#!/bin/bash")
    ///     .with_mode(0o755);
    ///
    /// assert_eq!(file.mode, Some(0o755));
    /// ```
    pub fn with_mode(mut self, mode: u32) -> Self {
        self.mode = Some(mode);
        self
    }
}

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

    #[test]
    fn test_directory_node() {
        let node = FileTreeNode::directory("src");
        assert_eq!(node.node_type, NodeType::Directory);
        assert_eq!(node.name, "src");
        assert!(node.children.is_empty());
    }

    #[test]
    fn test_file_node_with_content() {
        let node = FileTreeNode::file_with_content("main.rs", "fn main() {}");
        assert_eq!(node.node_type, NodeType::File);
        assert_eq!(node.name, "main.rs");
        assert_eq!(node.content, Some("fn main() {}".to_string()));
        assert_eq!(node.template, None);
    }

    #[test]
    fn test_file_node_with_template() {
        let node = FileTreeNode::file_with_template("lib.rs", "templates/lib.rs.tera");
        assert_eq!(node.node_type, NodeType::File);
        assert_eq!(node.name, "lib.rs");
        assert_eq!(node.template, Some("templates/lib.rs.tera".to_string()));
        assert_eq!(node.content, None);
    }

    #[test]
    fn test_template_format_creation() {
        let mut format = TemplateFormat::new("test-template");
        format.add_variable("service_name");
        format.add_default("port", "8080");

        assert_eq!(format.name, "test-template");
        assert_eq!(format.variables, vec!["service_name"]);
        assert_eq!(format.defaults.get("port"), Some(&"8080".to_string()));
    }

    #[test]
    fn test_template_format_validation() {
        let mut format = TemplateFormat::new("test");
        format.add_node(FileTreeNode::directory("src"));

        assert!(format.validate().is_ok());
    }

    #[test]
    fn test_empty_template_validation_fails() {
        let format = TemplateFormat::new("test");
        assert!(format.validate().is_err());
    }
}