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
//! Error types for lifecycle management
//!
//! This module provides rich, context-aware error types for all lifecycle operations,
//! following Rust best practices with thiserror.

use std::path::PathBuf;
use thiserror::Error;

/// Main error type for lifecycle operations
#[derive(Error, Debug)]
pub enum LifecycleError {
    /// Error loading or parsing make.toml configuration
    #[error("Failed to load configuration from {path}: {source}")]
    ConfigLoad {
        path: PathBuf,
        #[source]
        source: Box<dyn std::error::Error + Send + Sync>,
    },

    /// Error parsing make.toml TOML format
    #[error("Failed to parse TOML configuration at {path}: {source}")]
    ConfigParse {
        path: PathBuf,
        #[source]
        source: toml::de::Error,
    },

    /// Phase not found in configuration
    #[error("Phase '{phase}' not found in configuration")]
    PhaseNotFound { phase: String },

    /// Phase has no commands defined
    #[error("Phase '{phase}' has no commands defined")]
    NoCommands { phase: String },

    /// Command execution failure
    #[error("Command failed in phase '{phase}': {command}\n  Exit code: {exit_code}\n  Stderr: {stderr}")]
    CommandFailed {
        phase: String,
        command: String,
        exit_code: i32,
        stderr: String,
    },

    /// Command spawn failure
    #[error("Failed to spawn command in phase '{phase}': {command}")]
    CommandSpawn {
        phase: String,
        command: String,
        #[source]
        source: std::io::Error,
    },

    /// Hook recursion detected (circular dependency)
    #[error("Hook recursion detected: phase '{phase}' called recursively through chain: {}", chain.join(" -> "))]
    HookRecursion { phase: String, chain: Vec<String> },

    /// Hook execution failed
    #[error("Hook failed for phase '{phase}': {hook_phase}")]
    HookFailed {
        phase: String,
        hook_phase: String,
        #[source]
        source: Box<LifecycleError>,
    },

    /// State file load error
    #[error("Failed to load state from {path}: {source}")]
    StateLoad {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    /// State file parse error
    #[error("Failed to parse state JSON from {path}: {source}")]
    StateParse {
        path: PathBuf,
        #[source]
        source: serde_json::Error,
    },

    /// State file save error
    #[error("Failed to save state to {path}: {source}")]
    StateSave {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    /// Cache directory error
    #[error("Invalid cache path: {path}")]
    InvalidCachePath { path: PathBuf },

    /// Cache creation error
    #[error("Failed to create cache directory for phase '{phase}': {source}")]
    CacheCreate {
        phase: String,
        #[source]
        source: std::io::Error,
    },

    /// File I/O error with context
    #[error("File I/O error at {path}: {source}")]
    FileIo {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    /// Directory creation error
    #[error("Failed to create directory {path}: {source}")]
    DirectoryCreate {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    /// Make.toml load error
    #[error("Failed to load make.toml from {path}: {source}")]
    MakeTomlLoad {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    /// Make.toml parse error
    #[error("Failed to parse make.toml at {path}: {source}")]
    MakeTomlParse {
        path: PathBuf,
        #[source]
        source: toml::de::Error,
    },

    /// Workspace not found
    #[error("Workspace '{workspace}' not found in configuration")]
    WorkspaceNotFound { workspace: String },

    /// Workspace path error
    #[error("Invalid workspace path '{workspace}': {path}")]
    WorkspacePath { workspace: String, path: PathBuf },

    /// Parallel execution error
    #[error("Parallel execution failed for workspace '{workspace}': {source}")]
    ParallelExecution {
        workspace: String,
        #[source]
        source: Box<LifecycleError>,
    },

    /// Environment variable error
    #[error("Invalid environment variable: {key}={value}")]
    InvalidEnv { key: String, value: String },

    /// Mutex poisoned error (should never happen in normal operation)
    #[error("Internal error: mutex poisoned in phase '{phase}'")]
    MutexPoisoned { phase: String },

    /// Generic I/O error
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),

    /// Dependency cycle detected
    #[error("Circular dependency detected in phase dependencies: {phases}")]
    DependencyCycle { phases: String },

    /// Generic error for compatibility
    #[error("{0}")]
    Other(String),
}

impl LifecycleError {
    /// Create a config load error
    pub fn config_load(
        path: impl Into<PathBuf>, source: impl std::error::Error + Send + Sync + 'static,
    ) -> Self {
        Self::ConfigLoad {
            path: path.into(),
            source: Box::new(source),
        }
    }

    /// Create a config parse error
    pub fn config_parse(path: impl Into<PathBuf>, source: toml::de::Error) -> Self {
        Self::ConfigParse {
            path: path.into(),
            source,
        }
    }

    /// Create a phase not found error
    pub fn phase_not_found(phase: impl Into<String>) -> Self {
        Self::PhaseNotFound {
            phase: phase.into(),
        }
    }

    /// Create a command failed error
    pub fn command_failed(
        phase: impl Into<String>, command: impl Into<String>, exit_code: i32,
        stderr: impl Into<String>,
    ) -> Self {
        Self::CommandFailed {
            phase: phase.into(),
            command: command.into(),
            exit_code,
            stderr: stderr.into(),
        }
    }

    /// Create a command spawn error
    pub fn command_spawn(
        phase: impl Into<String>, command: impl Into<String>, source: std::io::Error,
    ) -> Self {
        Self::CommandSpawn {
            phase: phase.into(),
            command: command.into(),
            source,
        }
    }

    /// Create a hook recursion error with call chain
    pub fn hook_recursion_with_chain(phase: impl Into<String>, chain: Vec<String>) -> Self {
        Self::HookRecursion {
            phase: phase.into(),
            chain,
        }
    }

    /// Create a simple hook recursion error (for backward compatibility)
    pub fn hook_recursion(phase: impl Into<String>) -> Self {
        let phase_str = phase.into();
        Self::HookRecursion {
            phase: phase_str.clone(),
            chain: vec![phase_str],
        }
    }

    /// Create a state load error
    pub fn state_load(path: impl Into<PathBuf>, source: std::io::Error) -> Self {
        Self::StateLoad {
            path: path.into(),
            source,
        }
    }

    /// Create a state parse error
    pub fn state_parse(path: impl Into<PathBuf>, source: serde_json::Error) -> Self {
        Self::StateParse {
            path: path.into(),
            source,
        }
    }

    /// Create a state save error
    pub fn state_save(path: impl Into<PathBuf>, source: std::io::Error) -> Self {
        Self::StateSave {
            path: path.into(),
            source,
        }
    }

    /// Create an invalid cache path error
    pub fn invalid_cache_path(path: impl Into<PathBuf>) -> Self {
        Self::InvalidCachePath { path: path.into() }
    }

    /// Create a cache create error
    pub fn cache_create(phase: impl Into<String>, source: std::io::Error) -> Self {
        Self::CacheCreate {
            phase: phase.into(),
            source,
        }
    }

    /// Create a file I/O error
    pub fn file_io(path: impl Into<PathBuf>, source: std::io::Error) -> Self {
        Self::FileIo {
            path: path.into(),
            source,
        }
    }

    /// Create a directory creation error
    pub fn directory_create(path: impl Into<PathBuf>, source: std::io::Error) -> Self {
        Self::DirectoryCreate {
            path: path.into(),
            source,
        }
    }

    /// Create a make.toml load error
    pub fn make_toml_load(path: impl Into<PathBuf>, source: std::io::Error) -> Self {
        Self::MakeTomlLoad {
            path: path.into(),
            source,
        }
    }

    /// Create a make.toml parse error
    pub fn make_toml_parse(path: impl Into<PathBuf>, source: toml::de::Error) -> Self {
        Self::MakeTomlParse {
            path: path.into(),
            source,
        }
    }

    /// Create a parallel execution error
    pub fn parallel_execution(workspace: impl Into<String>, source: LifecycleError) -> Self {
        Self::ParallelExecution {
            workspace: workspace.into(),
            source: Box::new(source),
        }
    }

    /// Create a dependency cycle error
    pub fn dependency_cycle(phases: impl Into<String>) -> Self {
        Self::DependencyCycle {
            phases: phases.into(),
        }
    }
}

/// Result type alias for lifecycle operations
pub type Result<T> = std::result::Result<T, LifecycleError>;

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

    #[test]
    fn test_phase_not_found_error() {
        let err = LifecycleError::phase_not_found("build");
        assert_eq!(err.to_string(), "Phase 'build' not found in configuration");
    }

    #[test]
    fn test_command_failed_error() {
        let err = LifecycleError::command_failed("test", "cargo test", 101, "test failed");
        let msg = err.to_string();
        assert!(msg.contains("Command failed"));
        assert!(msg.contains("Exit code: 101"));
        assert!(msg.contains("test failed"));
    }

    #[test]
    fn test_hook_recursion_error() {
        let err = LifecycleError::hook_recursion("build");
        let msg = err.to_string();
        assert!(msg.contains("Hook recursion detected"));
        assert!(msg.contains("build"));
    }

    #[test]
    fn test_hook_recursion_with_chain() {
        let chain = vec![
            "init".to_string(),
            "setup".to_string(),
            "build".to_string(),
            "init".to_string(),
        ];
        let err = LifecycleError::hook_recursion_with_chain("init", chain);
        let msg = err.to_string();
        assert!(msg.contains("init -> setup -> build -> init"));
    }

    #[test]
    fn test_state_errors() {
        let path = PathBuf::from("/tmp/state.json");

        // Test state load error
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "not found");
        let err = LifecycleError::state_load(&path, io_err);
        assert!(err.to_string().contains("Failed to load state"));

        // Test state save error
        let io_err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied");
        let err = LifecycleError::state_save(&path, io_err);
        assert!(err.to_string().contains("Failed to save state"));
    }

    #[test]
    fn test_make_toml_errors() {
        let path = PathBuf::from("/tmp/make.toml");

        // Test load error
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "not found");
        let err = LifecycleError::make_toml_load(&path, io_err);
        assert!(err.to_string().contains("Failed to load make.toml"));
        assert!(err.to_string().contains("/tmp/make.toml"));
    }

    #[test]
    fn test_cache_errors() {
        let path = PathBuf::from("/tmp/cache");

        // Test invalid cache path
        let err = LifecycleError::invalid_cache_path(&path);
        assert!(err.to_string().contains("Invalid cache path"));

        // Test cache create error
        let io_err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied");
        let err = LifecycleError::cache_create("build", io_err);
        assert!(err.to_string().contains("Failed to create cache directory"));
        assert!(err.to_string().contains("build"));
    }

    #[test]
    fn test_error_downcasting() {
        let err = LifecycleError::phase_not_found("build");
        let err_ref: &dyn std::error::Error = &err;
        assert!(err_ref.source().is_none());

        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "not found");
        let err = LifecycleError::state_load("/tmp/state.json", io_err);
        let err_ref: &dyn std::error::Error = &err;
        assert!(err_ref.source().is_some());
    }

    #[test]
    fn test_error_display() {
        let lifecycle_err = LifecycleError::phase_not_found("test");
        let err_str = lifecycle_err.to_string();
        assert!(err_str.contains("Phase 'test' not found"));
    }
}