ggen-core 26.5.19

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
//! Architectural Integration Contracts
//!
//! This module defines trait-based contracts that enforce integration
//! boundaries between subsystems at compile time.
//!
//! # Design Principle
//!
//! Explicit contracts prevent integration failures by making API boundaries
//! type-safe and version-aware.

use std::path::Path;
use thiserror::Error;

// ============================================================================
// Core Contracts
// ============================================================================

/// Contract for any system that provides templates to the CLI
///
/// This trait defines the required interface that all template provider
/// implementations must satisfy. The compiler enforces that all methods
/// are implemented and type-safe.
///
/// # Examples
///
/// ```rust
/// use crate::prevention::contracts::TemplateProvider;
///
/// struct FilesystemProvider { /* ... */ }
///
/// impl TemplateProvider for FilesystemProvider {
///     fn discover(&self, path: &Path) -> Result<Vec<Template>, ProviderError> {
///         // Implementation
///     }
///     // ... other methods
/// }
/// ```
pub trait TemplateProvider: Send + Sync {
    /// Discover all templates in the given path
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - Path does not exist
    /// - Permission denied
    /// - IO error during discovery
    fn discover(&self, path: &Path) -> Result<Vec<Template>, ProviderError>;

    /// Validate a template's structure and syntax
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - Template syntax is invalid
    /// - Required fields missing
    /// - Constraints violated
    fn validate(&self, template: &Template) -> Result<(), ProviderError>;

    /// Render a template with the given context
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - Template is invalid
    /// - Context missing required variables
    /// - Rendering engine failure
    fn render(&self, template: &Template, context: Context) -> Result<String, ProviderError>;

    /// Get template metadata
    ///
    /// # Errors
    ///
    /// Returns error if template metadata cannot be read
    fn metadata(&self, template: &Template) -> Result<TemplateMetadata, ProviderError>;

    /// Get provider version (for compatibility checking)
    fn version(&self) -> Version {
        Version::new(1, 0, 0)
    }
}

/// Contract for CLI bridge implementations
///
/// This trait defines the interface between the CLI parser and the
/// command execution system.
pub trait CliBridge: Send + Sync {
    /// Parse CLI arguments into structured command
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - Invalid arguments
    /// - Missing required arguments
    /// - Parsing failure
    fn parse(&self, args: Vec<String>) -> Result<Command, BridgeError>;

    /// Execute command with template provider
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - Command execution fails
    /// - Provider error
    /// - Output formatting error
    fn execute<P: TemplateProvider>(
        &self,
        cmd: Command,
        provider: &P,
    ) -> Result<Output, BridgeError>;

    /// Format output for display
    fn format(&self, output: Output) -> String;

    /// Get bridge version (for compatibility checking)
    fn version(&self) -> Version {
        Version::new(1, 0, 0)
    }
}

/// Contract for rendering engines
///
/// This trait allows multiple rendering engine implementations
/// (Handlebars, Tera, Liquid, etc.) to be used interchangeably.
pub trait RenderEngine: Send + Sync {
    /// Render template content with context
    ///
    /// # Errors
    ///
    /// Returns error if rendering fails
    fn render(&self, content: &str, context: &Context) -> Result<String, RenderError>;

    /// Validate template syntax
    ///
    /// # Errors
    ///
    /// Returns error if syntax is invalid
    fn validate_syntax(&self, content: &str) -> Result<(), RenderError>;

    /// Get supported features
    fn features(&self) -> RenderFeatures;
}

// ============================================================================
// Supporting Types
// ============================================================================

/// Template representation
#[derive(Debug, Clone)]
pub struct Template {
    pub name: String,
    pub path: String,
    pub content: String,
}

/// Template metadata
#[derive(Debug, Clone)]
pub struct TemplateMetadata {
    pub name: String,
    pub version: Version,
    pub author: Option<String>,
    pub description: Option<String>,
    pub tags: Vec<String>,
}

/// Rendering context
#[derive(Debug, Clone, Default)]
pub struct Context {
    pub variables: std::collections::HashMap<String, serde_json::Value>,
}

/// CLI command representation
#[derive(Debug, Clone)]
pub struct Command {
    pub action: CommandAction,
    pub args: Vec<String>,
    pub flags: std::collections::HashMap<String, String>,
}

/// Command actions
#[derive(Debug, Clone)]
pub enum CommandAction {
    Generate,
    List,
    Validate,
    Search,
}

/// Command output
#[derive(Debug, Clone)]
pub struct Output {
    pub success: bool,
    pub message: String,
    pub data: Option<serde_json::Value>,
}

/// Version representation
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Version {
    pub major: u32,
    pub minor: u32,
    pub patch: u32,
}

impl Version {
    pub fn new(major: u32, minor: u32, patch: u32) -> Self {
        Self {
            major,
            minor,
            patch,
        }
    }

    /// Check if this version is compatible with another version
    ///
    /// Compatible if:
    /// - Major versions match (breaking changes)
    /// - This version >= other version
    pub fn is_compatible_with(&self, other: &Version) -> bool {
        self.major == other.major && self >= other
    }
}

impl std::fmt::Display for Version {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
    }
}

/// Render engine features
#[derive(Debug, Clone)]
pub struct RenderFeatures {
    pub supports_partials: bool,
    pub supports_helpers: bool,
    pub supports_filters: bool,
    pub supports_inheritance: bool,
}

// ============================================================================
// Error Types
// ============================================================================

#[derive(Error, Debug)]
pub enum ProviderError {
    #[error("Template not found: {path}")]
    TemplateNotFound { path: String },

    #[error("Invalid template syntax: {reason}")]
    InvalidSyntax { reason: String },

    #[error("Validation failed: {reason}")]
    ValidationFailed { reason: String },

    #[error("Rendering failed: {reason}")]
    RenderingFailed { reason: String },

    #[error("Version incompatibility: expected {expected}, got {actual}")]
    VersionIncompatible { expected: String, actual: String },

    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
}

#[derive(Error, Debug)]
pub enum BridgeError {
    #[error("Invalid command: {command}")]
    InvalidCommand { command: String },

    #[error("Missing required argument: {arg}")]
    MissingArgument { arg: String },

    #[error("Execution failed: {reason}")]
    ExecutionFailed { reason: String },

    #[error("Provider error: {0}")]
    Provider(#[from] ProviderError),
}

#[derive(Error, Debug)]
pub enum RenderError {
    #[error("Syntax error at line {line}, column {column}: {message}")]
    SyntaxError {
        line: usize,
        column: usize,
        message: String,
    },

    #[error("Missing variable: {variable}")]
    MissingVariable { variable: String },

    #[error("Rendering failed: {reason}")]
    RenderingFailed { reason: String },
}

// ============================================================================
// Contract Verification
// ============================================================================

/// Verify that a template provider satisfies the contract
///
/// This function can be used in tests to ensure all implementations
/// behave correctly according to the contract.
///
/// # Examples
///
/// ```rust
/// #[test]
/// fn test_filesystem_provider_contract() {
///     let provider = FilesystemTemplateProvider::new();
///     verify_template_provider_contract(provider).unwrap();
/// }
/// ```
#[cfg(test)]
pub fn verify_template_provider_contract<P: TemplateProvider>(
    provider: P,
) -> Result<(), String> {
    use std::path::PathBuf;

    // Contract requirement: discover must return valid templates
    let test_path = PathBuf::from("tests/fixtures/templates");
    let templates = provider
        .discover(&test_path)
        .map_err(|e| format!("discover failed: {}", e))?;

    if templates.is_empty() {
        return Err("Contract violation: discover returned empty list for valid path".to_string());
    }

    // Contract requirement: all discovered templates must be valid
    for template in &templates {
        provider
            .validate(template)
            .map_err(|e| format!("validate failed for {}: {}", template.name, e))?;
    }

    // Contract requirement: render must succeed for valid template
    if let Some(template) = templates.first() {
        let context = Context::default();
        provider
            .render(template, context)
            .map_err(|e| format!("render failed: {}", e))?;
    }

    // Contract requirement: metadata must be available
    if let Some(template) = templates.first() {
        let _metadata = provider
            .metadata(template)
            .map_err(|e| format!("metadata failed: {}", e))?;
    }

    Ok(())
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_version_compatibility() {
        let v1_0_0 = Version::new(1, 0, 0);
        let v1_1_0 = Version::new(1, 1, 0);
        let v2_0_0 = Version::new(2, 0, 0);

        // Same major version, newer minor version is compatible
        assert!(v1_1_0.is_compatible_with(&v1_0_0));

        // Different major version is not compatible
        assert!(!v2_0_0.is_compatible_with(&v1_0_0));

        // Older version is not compatible with newer
        assert!(!v1_0_0.is_compatible_with(&v1_1_0));
    }

    #[test]
    fn test_version_display() {
        let version = Version::new(1, 2, 3);
        assert_eq!(version.to_string(), "1.2.3");
    }

    // Example implementation for testing
    struct MockTemplateProvider;

    impl TemplateProvider for MockTemplateProvider {
        fn discover(&self, _path: &Path) -> Result<Vec<Template>, ProviderError> {
            Ok(vec![Template {
                name: "test".to_string(),
                path: "test.tmpl".to_string(),
                content: "{{ name }}".to_string(),
            }])
        }

        fn validate(&self, _template: &Template) -> Result<(), ProviderError> {
            Ok(())
        }

        fn render(&self, template: &Template, _context: Context) -> Result<String, ProviderError> {
            Ok(template.content.clone())
        }

        fn metadata(&self, template: &Template) -> Result<TemplateMetadata, ProviderError> {
            Ok(TemplateMetadata {
                name: template.name.clone(),
                version: Version::new(1, 0, 0),
                author: None,
                description: None,
                tags: vec![],
            })
        }
    }

    #[test]
    fn test_mock_provider_satisfies_contract() {
        let provider = MockTemplateProvider;
        verify_template_provider_contract(provider).unwrap();
    }
}