ggen-core 26.6.25

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
//! Developer Experience (DX) utilities for lifecycle operations
//!
//! This module provides quality-of-life improvements for developers:
//! - Progress indicators with colored output
//! - Verbose logging mode
//! - Execution summaries and metrics
//! - State visualization

use super::state::LifecycleState;
use colored::*;
use std::time::{Duration, Instant};

/// Boolean display flags for execution mode
#[allow(clippy::struct_excessive_bools)] // Four bools are semantically distinct display control flags
#[derive(Debug, Clone, Copy)]
pub struct DisplayFlags {
    /// Enable verbose output (shows all commands before execution)
    pub verbose: bool,
    /// Dry run mode (show what would be done without executing)
    pub dry_run: bool,
    /// Show progress indicators
    pub show_progress: bool,
    /// Use colored output
    pub use_colors: bool,
}

impl Default for DisplayFlags {
    fn default() -> Self {
        Self {
            verbose: false,
            dry_run: false,
            show_progress: true,
            use_colors: true,
        }
    }
}

/// Execution mode configuration
#[derive(Debug, Clone)]
pub struct ExecutionMode {
    /// Display and behavior flags
    pub flags: DisplayFlags,
}

impl Default for ExecutionMode {
    fn default() -> Self {
        Self {
            flags: DisplayFlags::default(),
        }
    }
}

impl ExecutionMode {
    /// Create execution mode for CI/CD (no colors, no progress)
    pub fn ci() -> Self {
        Self {
            flags: DisplayFlags {
                verbose: false,
                dry_run: false,
                show_progress: false,
                use_colors: false,
            },
        }
    }

    /// Create verbose mode
    pub fn verbose() -> Self {
        Self {
            flags: DisplayFlags {
                verbose: true,
                ..Default::default()
            },
        }
    }

    /// Create dry-run mode
    pub fn dry_run() -> Self {
        Self {
            flags: DisplayFlags {
                dry_run: true,
                verbose: true, // Always verbose in dry-run
                ..Default::default()
            },
        }
    }
}

/// Execution metrics tracker
#[derive(Debug, Clone)]
pub struct ExecutionMetrics {
    /// Overall start time
    start_time: Instant,
    /// Phase execution times (phase_name -> duration_ms)
    phase_times: Vec<(String, u128)>,
    /// Commands executed count
    commands_executed: usize,
    /// Hooks executed count
    hooks_executed: usize,
    /// Cache hits
    cache_hits: usize,
}

impl ExecutionMetrics {
    /// Create new metrics tracker
    pub fn new() -> Self {
        Self {
            start_time: Instant::now(),
            phase_times: Vec::new(),
            commands_executed: 0,
            hooks_executed: 0,
            cache_hits: 0,
        }
    }

    /// Record a phase execution
    pub fn record_phase(&mut self, phase: String, duration_ms: u128) {
        self.phase_times.push((phase, duration_ms));
    }

    /// Increment commands executed
    pub fn record_command(&mut self) {
        self.commands_executed += 1;
    }

    /// Increment hooks executed
    pub fn record_hook(&mut self) {
        self.hooks_executed += 1;
    }

    /// Increment cache hits
    pub fn record_cache_hit(&mut self) {
        self.cache_hits += 1;
    }

    /// Get total elapsed time
    pub fn total_elapsed(&self) -> Duration {
        self.start_time.elapsed()
    }

    /// Get summary report
    pub fn summary(&self, mode: &ExecutionMode) -> String {
        let mut report = String::new();
        let total = self.total_elapsed();

        if mode.flags.use_colors {
            report.push_str(&format!(
                "\n{}\n",
                "═══ Execution Summary ═══".bright_cyan().bold()
            ));

            // Total time
            report.push_str(&format!(
                "  {} {}\n",
                "⏱️  Total time:".bright_white(),
                format_duration(total).bright_green()
            ));

            // Phase breakdown
            if !self.phase_times.is_empty() {
                report.push_str(&format!(
                    "\n  {} {}\n",
                    "📊 Phase timing:".bright_white(),
                    ""
                ));
                for (phase, duration_ms) in &self.phase_times {
                    let percent = (*duration_ms as f64 / total.as_millis() as f64) * 100.0;
                    report.push_str(&format!(
                        "    {} {} {} {}\n",
                        "".bright_blue(),
                        phase.bright_yellow(),
                        format!("{}ms", duration_ms).bright_white(),
                        format!("({}%)", percent as u32).dimmed()
                    ));
                }
            }

            // Statistics
            report.push_str(&format!("\n  {} {}\n", "📈 Statistics:".bright_white(), ""));
            report.push_str(&format!(
                "    {} Phases executed: {}\n",
                "".bright_blue(),
                self.phase_times.len().to_string().bright_green()
            ));
            report.push_str(&format!(
                "    {} Commands run: {}\n",
                "".bright_blue(),
                self.commands_executed.to_string().bright_green()
            ));
            report.push_str(&format!(
                "    {} Hooks triggered: {}\n",
                "".bright_blue(),
                self.hooks_executed.to_string().bright_green()
            ));
            if self.cache_hits > 0 {
                report.push_str(&format!(
                    "    {} Cache hits: {} {}\n",
                    "".bright_blue(),
                    self.cache_hits.to_string().bright_green(),
                    "".bright_yellow()
                ));
            }

            report.push_str(&format!(
                "\n{}\n",
                "═════════════════════════".bright_cyan()
            ));
        } else {
            // Plain text for CI/CD
            report.push_str("\n=== Execution Summary ===\n");
            report.push_str(&format!("Total time: {}\n", format_duration(total)));
            report.push_str(&format!("Phases: {}\n", self.phase_times.len()));
            report.push_str(&format!("Commands: {}\n", self.commands_executed));
            report.push_str(&format!("Hooks: {}\n", self.hooks_executed));
            if self.cache_hits > 0 {
                report.push_str(&format!("Cache hits: {}\n", self.cache_hits));
            }
            report.push_str("=========================\n");
        }

        report
    }
}

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

/// Output helper for consistent messaging
pub struct Output {
    mode: ExecutionMode,
}

impl Output {
    /// Create new output helper
    pub fn new(mode: ExecutionMode) -> Self {
        Self { mode }
    }

    /// Print info message
    pub fn info(&self, msg: &str) {
        if self.mode.flags.use_colors {
            log::info!("{} {}", "".bright_blue(), msg);
        } else {
            log::info!("[INFO] {}", msg);
        }
    }

    /// Print success message
    pub fn success(&self, msg: &str) {
        if self.mode.flags.use_colors {
            log::info!("{} {}", "".bright_green(), msg.bright_green());
        } else {
            log::info!("[SUCCESS] {}", msg);
        }
    }

    /// Print warning message
    pub fn warning(&self, msg: &str) {
        if self.mode.flags.use_colors {
            log::warn!("{} {}", "".bright_yellow(), msg.yellow());
        } else {
            log::warn!("[WARNING] {}", msg);
        }
    }

    /// Print error message
    pub fn error(&self, msg: &str) {
        if self.mode.flags.use_colors {
            log::error!("{} {}", "".bright_red(), msg.red());
        } else {
            log::error!("[ERROR] {}", msg);
        }
    }

    /// Print phase start
    pub fn phase_start(&self, phase: &str) {
        if self.mode.flags.use_colors {
            log::info!(
                "\n{} {}",
                "".bright_cyan().bold(),
                phase.bright_cyan().bold()
            );
        } else {
            log::info!("\n[PHASE] {}", phase);
        }
    }

    /// Print phase complete
    pub fn phase_complete(&self, phase: &str, duration_ms: u128) {
        if self.mode.flags.use_colors {
            log::info!(
                "{} {} {} {}",
                "".bright_green(),
                phase.bright_green(),
                "completed in".dimmed(),
                format!("{}ms", duration_ms).bright_white()
            );
        } else {
            log::info!("[COMPLETE] {} ({}ms)", phase, duration_ms);
        }
    }

    /// Print command execution (verbose only)
    pub fn command(&self, cmd: &str) {
        if self.mode.flags.verbose {
            if self.mode.flags.use_colors {
                log::debug!("  {} {}", "$".bright_blue(), cmd.dimmed());
            } else {
                log::debug!("  $ {}", cmd);
            }
        }
    }

    /// Print dry-run command
    pub fn dry_run(&self, cmd: &str) {
        if self.mode.flags.use_colors {
            log::info!("  {} {}", "[DRY-RUN]".bright_magenta().bold(), cmd.dimmed());
        } else {
            log::info!("  [DRY-RUN] {}", cmd);
        }
    }

    /// Print hook execution
    pub fn hook(&self, hook_type: &str, phase: &str) {
        if self.mode.flags.verbose {
            if self.mode.flags.use_colors {
                log::debug!(
                    "  {} {} {}",
                    "".bright_yellow(),
                    hook_type.yellow(),
                    phase.dimmed()
                );
            } else {
                log::debug!("  [HOOK] {} {}", hook_type, phase);
            }
        }
    }

    /// Print cache hit
    pub fn cache_hit(&self, phase: &str) {
        if self.mode.flags.verbose {
            if self.mode.flags.use_colors {
                log::debug!(
                    "  {} {} {}",
                    "".bright_yellow(),
                    "Cache hit for".dimmed(),
                    phase.yellow()
                );
            } else {
                log::debug!("  [CACHE] Hit for {}", phase);
            }
        }
    }

    /// Print workspace
    pub fn workspace(&self, name: &str) {
        if self.mode.flags.use_colors {
            log::info!(
                "\n{} {}",
                "📦".bright_magenta(),
                name.bright_magenta().bold()
            );
        } else {
            log::info!("\n[WORKSPACE] {}", name);
        }
    }
}

/// State visualization helper
pub struct StateVisualizer {
    use_colors: bool,
}

impl StateVisualizer {
    /// Create new state visualizer
    pub fn new(use_colors: bool) -> Self {
        Self { use_colors }
    }

    /// Pretty-print lifecycle state
    pub fn display(&self, state: &LifecycleState) -> String {
        let mut output = String::new();

        if self.use_colors {
            output.push_str(&format!(
                "\n{}\n",
                "━━━ Lifecycle State ━━━".bright_cyan().bold()
            ));

            // Last phase
            if let Some(last) = &state.last_phase {
                output.push_str(&format!(
                    "  {} {}\n",
                    "Last phase:".bright_white(),
                    last.bright_yellow()
                ));
            } else {
                output.push_str(&format!(
                    "  {} {}\n",
                    "Last phase:".bright_white(),
                    "None".dimmed()
                ));
            }

            // Phase history
            if !state.phase_history.is_empty() {
                output.push_str(&format!(
                    "\n  {} {}\n",
                    "Recent executions:".bright_white(),
                    ""
                ));
                let recent = state.phase_history.iter().rev().take(10);
                for record in recent {
                    let status = if record.success {
                        "".bright_green()
                    } else {
                        "".bright_red()
                    };
                    output.push_str(&format!(
                        "    {} {} {} {}\n",
                        status,
                        record.phase.bright_yellow(),
                        format!("({}ms)", record.duration_ms).dimmed(),
                        format_timestamp(record.started_ms).dimmed()
                    ));
                }
                if state.phase_history.len() > 10 {
                    output.push_str(&format!(
                        "    {} {} more...\n",
                        "...".dimmed(),
                        (state.phase_history.len() - 10).to_string().dimmed()
                    ));
                }
            }

            // Cache keys
            if !state.cache_keys.is_empty() {
                output.push_str(&format!("\n  {} {}\n", "Cache keys:".bright_white(), ""));
                for key in state.cache_keys.iter().rev().take(5) {
                    output.push_str(&format!(
                        "    {} {} {}\n",
                        "".bright_blue(),
                        key.phase.bright_yellow(),
                        key.key[..8].dimmed()
                    ));
                }
            }

            output.push_str(&format!("\n{}\n", "━━━━━━━━━━━━━━━━━━━━━━━".bright_cyan()));
        } else {
            output.push_str("\n=== Lifecycle State ===\n");
            if let Some(last) = &state.last_phase {
                output.push_str(&format!("Last phase: {}\n", last));
            }
            output.push_str(&format!(
                "Total executions: {}\n",
                state.phase_history.len()
            ));
            output.push_str(&format!("Cache keys: {}\n", state.cache_keys.len()));
            output.push_str("=======================\n");
        }

        output
    }
}

/// Format duration in human-readable form
fn format_duration(duration: Duration) -> String {
    let millis = duration.as_millis();
    if millis < 1000 {
        format!("{}ms", millis)
    } else if millis < 60_000 {
        format!("{:.2}s", millis as f64 / 1000.0)
    } else {
        let secs = millis / 1000;
        let mins = secs / 60;
        let secs = secs % 60;
        format!("{}m {}s", mins, secs)
    }
}

/// Format timestamp in human-readable form
fn format_timestamp(timestamp_ms: u128) -> String {
    use std::time::{SystemTime, UNIX_EPOCH};

    let now_ms = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis())
        .unwrap_or(0); // Fallback to epoch if clock is invalid

    let diff_ms = now_ms.saturating_sub(timestamp_ms);

    if diff_ms < 1000 {
        "just now".to_string()
    } else if diff_ms < 60_000 {
        format!("{}s ago", diff_ms / 1000)
    } else if diff_ms < 3_600_000 {
        format!("{}m ago", diff_ms / 60_000)
    } else if diff_ms < 86_400_000 {
        format!("{}h ago", diff_ms / 3_600_000)
    } else {
        format!("{}d ago", diff_ms / 86_400_000)
    }
}

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

    #[test]
    fn test_execution_mode_defaults() {
        let mode = ExecutionMode::default();
        assert!(!mode.flags.verbose);
        assert!(!mode.flags.dry_run);
        assert!(mode.flags.show_progress);
        assert!(mode.flags.use_colors);
    }

    #[test]
    fn test_ci_mode() {
        let mode = ExecutionMode::ci();
        assert!(!mode.flags.show_progress);
        assert!(!mode.flags.use_colors);
    }

    #[test]
    fn test_metrics_tracking() {
        let mut metrics = ExecutionMetrics::new();
        metrics.record_phase("build".to_string(), 1000);
        metrics.record_command();
        metrics.record_command();
        metrics.record_hook();

        assert_eq!(metrics.phase_times.len(), 1);
        assert_eq!(metrics.commands_executed, 2);
        assert_eq!(metrics.hooks_executed, 1);
    }

    #[test]
    fn test_format_duration() {
        assert_eq!(format_duration(Duration::from_millis(500)), "500ms");
        assert_eq!(format_duration(Duration::from_millis(1500)), "1.50s");
        assert_eq!(format_duration(Duration::from_secs(90)), "1m 30s");
    }

    #[test]
    fn test_output_modes() {
        let output = Output::new(ExecutionMode::default());
        output.info("test");
        output.success("test");
        output.warning("test");
        output.phase_start("build");
        output.command("cargo build");
    }

    #[test]
    fn test_state_visualizer() {
        let state = LifecycleState::default();
        let viz = StateVisualizer::new(false);
        let display = viz.display(&state);
        assert!(display.contains("Lifecycle State"));
    }
}