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
//! Enhanced error handling with contextual help and platform-specific fixes
//!
//! This module provides enhanced error types that include contextual help,
//! platform-specific fix suggestions, and categorized error information.
//! It extends the base error handling with actionable guidance for users.
//!
//! ## Features
//!
//! - **Error Categorization**: Group errors by type (FileNotFound, PermissionDenied, etc.)
//! - **Platform-Specific Fixes**: Provide OS-specific solution suggestions
//! - **Contextual Help**: Include relevant documentation links and examples
//! - **Colorized Output**: Visual error formatting for better readability
//!
//! ## Error Categories
//!
//! - **FileNotFound**: File or directory not found
//! - **PermissionDenied**: Insufficient permissions
//! - **InvalidInput**: Invalid user input or configuration
//! - **NetworkError**: Network-related failures
//! - **ConfigurationError**: Configuration file issues
//! - **TemplateError**: Template parsing or rendering errors
//! - **DependencyError**: Missing or incompatible dependencies
//! - **BuildError**: Build or compilation errors
//!
//! ## Examples
//!
//! ### Creating an Enhanced Error
//!
//! ```rust,no_run
//! use crate::utils::enhanced_error::{EnhancedError, ErrorCategory, PlatformFix};
//!
//! # fn main() -> anyhow::Result<()> {
//! let fix = PlatformFix::new()
//!     .macos("Check file permissions: chmod +x script.sh")
//!     .linux("Check file permissions: chmod +x script.sh")
//!     .windows("Run as administrator or check file permissions");
//!
//! let error = EnhancedError::new(
//!     ErrorCategory::PermissionDenied,
//!     "Cannot execute script",
//! ).with_platform_fix(fix);
//! # Ok(())
//! # }
//! ```

use colored::Colorize;
use std::fmt;

/// Error category for better error grouping
///
/// Categorizes errors for better grouping and user experience.
///
/// # Examples
///
/// ```rust
/// use crate::utils::enhanced_error::ErrorCategory;
///
/// # fn main() {
/// let category = ErrorCategory::FileNotFound;
/// match category {
///     ErrorCategory::FileNotFound => assert!(true),
///     ErrorCategory::PermissionDenied => assert!(true),
///     ErrorCategory::InvalidInput => assert!(true),
///     ErrorCategory::NetworkError => assert!(true),
///     ErrorCategory::ConfigurationError => assert!(true),
///     ErrorCategory::TemplateError => assert!(true),
///     ErrorCategory::DependencyError => assert!(true),
///     ErrorCategory::BuildError => assert!(true),
///     ErrorCategory::Unknown => assert!(true),
/// }
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ErrorCategory {
    /// File not found error
    FileNotFound,
    /// Permission denied error
    PermissionDenied,
    /// Invalid input error
    InvalidInput,
    /// Network error
    NetworkError,
    /// Configuration error
    ConfigurationError,
    /// Template error
    TemplateError,
    /// Dependency error
    DependencyError,
    /// Build error
    BuildError,
    /// Unknown error
    Unknown,
}

/// Platform-specific fix suggestions
#[derive(Debug, Clone)]
pub struct PlatformFix {
    pub macos: Option<String>,
    pub linux: Option<String>,
    pub windows: Option<String>,
}

impl PlatformFix {
    pub fn new() -> Self {
        Self {
            macos: None,
            linux: None,
            windows: None,
        }
    }

    pub fn macos(mut self, fix: impl Into<String>) -> Self {
        self.macos = Some(fix.into());
        self
    }

    pub fn linux(mut self, fix: impl Into<String>) -> Self {
        self.linux = Some(fix.into());
        self
    }

    pub fn windows(mut self, fix: impl Into<String>) -> Self {
        self.windows = Some(fix.into());
        self
    }

    pub fn all_platforms(fix: impl Into<String>) -> Self {
        let fix_str = fix.into();
        Self {
            macos: Some(fix_str.clone()),
            linux: Some(fix_str.clone()),
            windows: Some(fix_str),
        }
    }

    #[cfg(target_os = "macos")]
    pub fn current_platform(&self) -> Option<&str> {
        self.macos.as_deref()
    }

    #[cfg(target_os = "linux")]
    pub fn current_platform(&self) -> Option<&str> {
        self.linux.as_deref()
    }

    #[cfg(target_os = "windows")]
    pub fn current_platform(&self) -> Option<&str> {
        self.windows.as_deref()
    }

    #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
    pub fn current_platform(&self) -> Option<&str> {
        None
    }
}

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

/// Enhanced error with contextual help
#[derive(Debug, Clone)]
pub struct EnhancedError {
    pub category: ErrorCategory,
    pub message: String,
    pub context: Option<String>,
    pub fix_suggestions: Vec<String>,
    pub platform_fixes: Option<PlatformFix>,
    pub did_you_mean: Option<Vec<String>>,
    pub related_docs: Option<String>,
}

impl EnhancedError {
    pub fn new(category: ErrorCategory, message: impl Into<String>) -> Self {
        Self {
            category,
            message: message.into(),
            context: None,
            fix_suggestions: Vec::new(),
            platform_fixes: None,
            did_you_mean: None,
            related_docs: None,
        }
    }

    pub fn with_context(mut self, context: impl Into<String>) -> Self {
        self.context = Some(context.into());
        self
    }

    pub fn with_fix(mut self, fix: impl Into<String>) -> Self {
        self.fix_suggestions.push(fix.into());
        self
    }

    pub fn with_fixes(mut self, fixes: Vec<String>) -> Self {
        self.fix_suggestions.extend(fixes);
        self
    }

    pub fn with_platform_fix(mut self, platform_fix: PlatformFix) -> Self {
        self.platform_fixes = Some(platform_fix);
        self
    }

    pub fn with_did_you_mean(mut self, suggestions: Vec<String>) -> Self {
        self.did_you_mean = Some(suggestions);
        self
    }

    pub fn with_docs(mut self, docs_url: impl Into<String>) -> Self {
        self.related_docs = Some(docs_url.into());
        self
    }

    /// Display the error with colored output and helpful context
    pub fn display_pretty(&self) {
        println!();
        println!("{} {}", "❌ Error:".red().bold(), self.message.red());

        if let Some(context) = &self.context {
            println!();
            println!("{} {}", "📝 Context:".yellow(), context.dimmed());
        }

        if let Some(suggestions) = &self.did_you_mean {
            println!();
            println!("{}", "💡 Did you mean:".cyan().bold());
            for suggestion in suggestions {
                println!("{}", suggestion.cyan());
            }
        }

        if !self.fix_suggestions.is_empty() {
            println!();
            println!("{}", "🔧 How to fix:".green().bold());
            for (i, fix) in self.fix_suggestions.iter().enumerate() {
                println!("   {}. {}", i + 1, fix);
            }
        }

        if let Some(platform_fixes) = &self.platform_fixes {
            if let Some(current_fix) = platform_fixes.current_platform() {
                println!();
                println!("{}", "🖥️  Platform-specific fix:".green().bold());
                println!("   {}", current_fix);
            }
        }

        if let Some(docs) = &self.related_docs {
            println!();
            println!("{} {}", "📚 Documentation:".blue(), docs);
        }

        println!();
    }
}

impl fmt::Display for EnhancedError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)?;
        if let Some(context) = &self.context {
            write!(f, " ({})", context)?;
        }
        Ok(())
    }
}

impl std::error::Error for EnhancedError {}

/// Common enhanced errors with contextual help
pub mod common_errors {
    use super::*;

    pub fn file_not_found(path: &str) -> EnhancedError {
        EnhancedError::new(
            ErrorCategory::FileNotFound,
            format!("File not found: {}", path),
        )
        .with_context("The specified file does not exist or is not accessible")
        .with_fix("Check that the file path is correct")
        .with_fix("Verify that you have permission to access the file")
        .with_fix("Try using an absolute path instead of a relative path")
        .with_platform_fix(
            PlatformFix::new()
                .macos("Use 'ls -la' to check file permissions")
                .linux("Use 'ls -la' to check file permissions")
                .windows("Use 'dir' or 'Get-ChildItem' to check file existence"),
        )
    }

    pub fn template_not_found(template_name: &str, available: Vec<String>) -> EnhancedError {
        let mut error = EnhancedError::new(
            ErrorCategory::TemplateError,
            format!("Template '{}' not found", template_name),
        )
        .with_context("The specified template does not exist in the registry")
        .with_fix("Run 'ggen list' to see available templates")
        .with_fix("Use 'ggen search <query>' to find templates")
        .with_docs("https://seanchatmangpt.github.io/ggen/templates");

        if !available.is_empty() {
            let suggestions = available
                .iter()
                .filter(|t| {
                    let name_lower = template_name.to_lowercase();
                    let t_lower = t.to_lowercase();
                    t_lower.contains(&name_lower) || name_lower.contains(&t_lower)
                })
                .take(3)
                .cloned()
                .collect::<Vec<_>>();

            if !suggestions.is_empty() {
                error = error.with_did_you_mean(suggestions);
            }
        }

        error
    }

    pub fn command_not_found(command: &str, available: Vec<String>) -> EnhancedError {
        let mut error = EnhancedError::new(
            ErrorCategory::InvalidInput,
            format!("Unknown command: {}", command),
        )
        .with_context("The command you entered is not recognized")
        .with_fix("Run 'ggen --help' to see all available commands")
        .with_fix("Check for typos in the command name");

        // Find similar commands using simple string distance
        let suggestions = available
            .iter()
            .filter(|cmd| {
                let cmd_lower = cmd.to_lowercase();
                let command_lower = command.to_lowercase();
                // Simple similarity check
                cmd_lower.starts_with(&command_lower)
                    || command_lower.starts_with(&cmd_lower)
                    || levenshtein_distance(&cmd_lower, &command_lower) <= 2
            })
            .take(3)
            .cloned()
            .collect::<Vec<_>>();

        if !suggestions.is_empty() {
            error = error.with_did_you_mean(suggestions);
        }

        error
    }

    pub fn missing_dependency(dependency: &str, install_cmd: &str) -> EnhancedError {
        EnhancedError::new(
            ErrorCategory::DependencyError,
            format!("Required dependency not found: {}", dependency),
        )
        .with_context("A required tool or library is not installed")
        .with_fix(format!("Install {} using: {}", dependency, install_cmd))
        .with_fix("Run 'ggen doctor' to check your environment")
        .with_platform_fix(
            PlatformFix::new()
                .macos(format!("brew install {}", dependency))
                .linux(format!("sudo apt install {}", dependency))
                .windows(format!("Use chocolatey: choco install {}", dependency)),
        )
    }

    pub fn permission_denied(path: &str) -> EnhancedError {
        EnhancedError::new(
            ErrorCategory::PermissionDenied,
            format!("Permission denied: {}", path),
        )
        .with_context("You don't have permission to access this file or directory")
        .with_fix("Check file permissions and ownership")
        .with_fix("Try running with appropriate permissions")
        .with_platform_fix(
            PlatformFix::new()
                .macos(format!("Use 'chmod +r {}' to add read permission", path))
                .linux(format!("Use 'chmod +r {}' to add read permission", path))
                .windows("Right-click the file and check security settings"),
        )
    }

    pub fn invalid_yaml(error_msg: &str) -> EnhancedError {
        EnhancedError::new(
            ErrorCategory::ConfigurationError,
            "Invalid YAML syntax in template frontmatter",
        )
        .with_context(error_msg)
        .with_fix("Check for indentation errors (YAML uses spaces, not tabs)")
        .with_fix("Ensure all strings with special characters are quoted")
        .with_fix("Verify that list items start with '- '")
        .with_fix("Use a YAML validator like yamllint")
        .with_docs("https://yaml.org/spec/1.2/spec.html")
    }

    pub fn network_error(url: &str) -> EnhancedError {
        EnhancedError::new(
            ErrorCategory::NetworkError,
            format!("Network request failed: {}", url),
        )
        .with_context("Could not reach the remote server")
        .with_fix("Check your internet connection")
        .with_fix("Verify the URL is correct")
        .with_fix("Check if you're behind a proxy or firewall")
        .with_fix("Try again in a few moments")
    }

    // Simple Levenshtein distance for "Did you mean?" suggestions
    fn levenshtein_distance(s1: &str, s2: &str) -> usize {
        let len1 = s1.len();
        let len2 = s2.len();
        let mut matrix = vec![vec![0; len2 + 1]; len1 + 1];

        for (i, row) in matrix.iter_mut().enumerate() {
            row[0] = i;
        }
        for j in 0..=len2 {
            matrix[0][j] = j;
        }

        for (i, c1) in s1.chars().enumerate() {
            for (j, c2) in s2.chars().enumerate() {
                let cost = if c1 == c2 { 0 } else { 1 };
                matrix[i + 1][j + 1] = (matrix[i][j + 1] + 1)
                    .min(matrix[i + 1][j] + 1)
                    .min(matrix[i][j] + cost);
            }
        }

        matrix[len1][len2]
    }
}

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

    #[test]
    fn test_enhanced_error_creation() {
        let error = EnhancedError::new(ErrorCategory::FileNotFound, "test.txt not found");
        assert_eq!(error.message, "test.txt not found");
        assert_eq!(error.category, ErrorCategory::FileNotFound);
    }

    #[test]
    fn test_error_with_context() {
        let error = EnhancedError::new(ErrorCategory::InvalidInput, "Invalid input")
            .with_context("Expected a number");
        assert_eq!(error.context, Some("Expected a number".to_string()));
    }

    #[test]
    fn test_error_with_fixes() {
        let error = EnhancedError::new(ErrorCategory::ConfigurationError, "Config error")
            .with_fix("Fix 1")
            .with_fix("Fix 2");
        assert_eq!(error.fix_suggestions.len(), 2);
    }

    #[test]
    fn test_platform_fix() {
        let fix = PlatformFix::new()
            .macos("brew install rust")
            .linux("apt install rust")
            .windows("choco install rust");

        assert!(fix.macos.is_some());
        assert!(fix.linux.is_some());
        assert!(fix.windows.is_some());
    }

    #[test]
    fn test_file_not_found_error() {
        let error = common_errors::file_not_found("test.txt");
        assert_eq!(error.category, ErrorCategory::FileNotFound);
        assert!(!error.fix_suggestions.is_empty());
    }

    #[test]
    fn test_command_not_found_with_suggestions() {
        let available = vec![
            "generate".to_string(),
            "list".to_string(),
            "search".to_string(),
        ];
        let error = common_errors::command_not_found("gen", available);
        assert!(error.did_you_mean.is_some());
    }
}