ai-code-buddy 0.4.20

An AI-powered code review tool with elegant Bevy-based TUI
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
use bevy::prelude::*;
use bevy_ratatui::{error::exit_on_error, terminal::RatatuiContext};
use bevy_tokio_tasks::TokioTasksRuntime;
use crossterm::event::{KeyCode, KeyEventKind};
use ratatui::{
    buffer::Buffer,
    layout::{Alignment, Constraint, Direction, Layout, Rect},
    style::Style,
    text::{Line, Span},
    widgets::{Block, Borders, Gauge, List, ListItem, Paragraph, StatefulWidgetRef, WidgetRef},
};

use crate::{
    args::Args,
    bevy_states::app::AppState,
    core,
    events::{analysis::AnalysisEvent, app::AppEvent},
    theme::THEME,
    widget_states::analysis::AnalysisWidgetState,
};

pub struct AnalysisPlugin;

impl Plugin for AnalysisPlugin {
    fn build(&self, app: &mut App) {
        app.add_event::<AnalysisEvent>()
            .init_resource::<AnalysisWidgetState>()
            .add_systems(PreUpdate, analysis_event_handler)
            .add_systems(Update, render_analysis.pipe(exit_on_error));
    }
}

pub fn analysis_event_handler(
    mut analysis_events: EventReader<AnalysisEvent>,
    mut analysis_state: ResMut<AnalysisWidgetState>,
    mut app_events: EventWriter<AppEvent>,
    args: Res<Args>,
    tokio_runtime: ResMut<TokioTasksRuntime>,
) {
    for event in analysis_events.read() {
        match event {
            AnalysisEvent::KeyEvent(key_event) => {
                match key_event.code {
                    KeyCode::Esc => {
                        // Always allow going back to overview with Escape
                        // If analysis is running, this will stop it and go back
                        if analysis_state.is_analyzing {
                            analysis_state.is_analyzing = false;
                        }
                        app_events.send(AppEvent::SwitchTo(AppState::Overview));
                    }
                    _ => {
                        // Only handle other keys on release to avoid double-triggering
                        if key_event.kind == KeyEventKind::Release {
                            match key_event.code {
                                KeyCode::Enter => {
                                    if !analysis_state.is_analyzing
                                        && analysis_state.review.is_none()
                                    {
                                        start_analysis(&mut analysis_state, &args, &tokio_runtime);
                                    }
                                }
                                KeyCode::Up => {
                                    if !analysis_state.is_analyzing {
                                        analysis_state.move_issue_selection(-1);
                                    }
                                }
                                KeyCode::Down => {
                                    if !analysis_state.is_analyzing {
                                        analysis_state.move_issue_selection(1);
                                    }
                                }
                                KeyCode::Char('r') => {
                                    if !analysis_state.is_analyzing {
                                        app_events.send(AppEvent::SwitchTo(AppState::Reports));
                                    }
                                }
                                _ => {}
                            }
                        }
                    }
                }
            }
            AnalysisEvent::MouseEvent(_mouse_event) => {
                // Handle mouse events if needed
            }
        }
    }
}

fn start_analysis(
    analysis_state: &mut AnalysisWidgetState,
    args: &Args,
    _tokio_runtime: &TokioTasksRuntime,
) {
    analysis_state.start_analysis();

    // Perform analysis synchronously to avoid GitAnalyzer Send issues
    match core::analysis::perform_analysis(args) {
        Ok(review) => {
            analysis_state.complete_analysis(review);
        }
        Err(e) => {
            eprintln!("AI analysis failed: {e}");
            analysis_state.is_analyzing = false;
        }
    }
}

fn render_analysis(
    app_state: Res<State<AppState>>,
    mut ratatui_context: ResMut<RatatuiContext>,
    mut analysis_state: ResMut<AnalysisWidgetState>,
) -> color_eyre::Result<()> {
    if app_state.get() != &AppState::Analysis {
        return Ok(());
    }

    ratatui_context.draw(|frame| {
        let area = frame.area();
        frame.render_stateful_widget_ref(AnalysisWidget, area, &mut analysis_state);
    })?;

    Ok(())
}

pub struct AnalysisWidget;

impl StatefulWidgetRef for AnalysisWidget {
    type State = AnalysisWidgetState;

    fn render_ref(&self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(3), // Title
                Constraint::Min(10),   // Content
                Constraint::Length(3), // Status bar
            ])
            .split(area);

        // Render title
        let title = Paragraph::new("🔍 Code Analysis")
            .style(THEME.title_style())
            .alignment(Alignment::Center)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_style(THEME.header_style()),
            );
        title.render_ref(chunks[0], buf);

        // Render content based on state
        if state.is_analyzing {
            self.render_analysis_progress(chunks[1], buf, state);
        } else if let Some(review) = &state.review {
            self.render_results(chunks[1], buf, state, review);
        } else {
            self.render_start_screen(chunks[1], buf);
        }

        // Render status bar
        self.render_status_bar(chunks[2], buf, state);
    }
}

impl AnalysisWidget {
    fn render_start_screen(&self, area: Rect, buf: &mut Buffer) {
        let content = Paragraph::new(vec![
            Line::from(""),
            Line::from("Press Enter to start the code analysis"),
            Line::from(""),
            Line::from("This will analyze your Git repository for:"),
            Line::from("â€ĸ Security vulnerabilities"),
            Line::from("â€ĸ Performance issues"),
            Line::from("â€ĸ Code quality problems"),
            Line::from("â€ĸ Best practice violations"),
        ])
        .alignment(Alignment::Center)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title("Ready to Analyze")
                .title_style(THEME.header_style()),
        );

        content.render_ref(area, buf);
    }

    fn render_analysis_progress(&self, area: Rect, buf: &mut Buffer, state: &AnalysisWidgetState) {
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(5), // Progress bar
                Constraint::Min(3),    // Current file
            ])
            .split(area);

        // Progress bar
        let progress = Gauge::default()
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .title("Analysis Progress")
                    .title_style(THEME.header_style()),
            )
            .gauge_style(THEME.success_style())
            .percent(state.progress as u16)
            .label(format!("{:.1}%", state.progress));

        progress.render_ref(chunks[0], buf);

        // Current file
        let current_file = Paragraph::new(vec![
            Line::from(""),
            Line::from(vec![
                Span::styled("Currently analyzing: ", THEME.info_style()),
                Span::raw(&state.current_file),
            ]),
        ])
        .alignment(Alignment::Center)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title("Status")
                .title_style(THEME.header_style()),
        );

        current_file.render_ref(chunks[1], buf);
    }

    fn render_results(
        &self,
        area: Rect,
        buf: &mut Buffer,
        state: &AnalysisWidgetState,
        review: &crate::core::review::Review,
    ) {
        let chunks = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Percentage(30), // Summary
                Constraint::Percentage(70), // Issue list
            ])
            .split(area);

        // Summary
        self.render_summary(chunks[0], buf, review);

        // Issue list
        self.render_issue_list(chunks[1], buf, state, review);
    }

    fn render_summary(&self, area: Rect, buf: &mut Buffer, review: &crate::core::review::Review) {
        let summary_lines = vec![
            Line::from(""),
            Line::from(vec![
                Span::styled("📁 Files: ", THEME.info_style()),
                Span::raw(format!("{}", review.files_count)),
            ]),
            Line::from(""),
            Line::from(vec![
                Span::styled("🐛 Total Issues: ", THEME.info_style()),
                Span::raw(format!("{}", review.issues_count)),
            ]),
            Line::from(""),
            Line::from(vec![
                Span::styled("🚨 Critical: ", THEME.error_style()),
                Span::raw(format!("{}", review.critical_issues)),
            ]),
            Line::from(vec![
                Span::styled("âš ī¸  High: ", THEME.warning_style()),
                Span::raw(format!("{}", review.high_issues)),
            ]),
            Line::from(vec![
                Span::styled("đŸ”ļ Medium: ", THEME.warning_style()),
                Span::raw(format!("{}", review.medium_issues)),
            ]),
            Line::from(vec![
                Span::styled("â„šī¸  Low: ", THEME.info_style()),
                Span::raw(format!("{}", review.low_issues)),
            ]),
        ];

        let summary = Paragraph::new(summary_lines).block(
            Block::default()
                .borders(Borders::ALL)
                .title("Summary")
                .title_style(THEME.header_style()),
        );

        summary.render_ref(area, buf);
    }

    fn render_issue_list(
        &self,
        area: Rect,
        buf: &mut Buffer,
        state: &AnalysisWidgetState,
        review: &crate::core::review::Review,
    ) {
        if review.issues.is_empty() {
            let no_issues = Paragraph::new(vec![
                Line::from(""),
                Line::from("🎉 No issues found!"),
                Line::from(""),
                Line::from("Your code looks clean. Great job!"),
            ])
            .alignment(Alignment::Center)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .title("Issues")
                    .title_style(THEME.header_style()),
            );
            no_issues.render_ref(area, buf);
            return;
        }

        let items: Vec<ListItem> = review
            .issues
            .iter()
            .enumerate()
            .map(|(i, issue)| {
                let severity_icon = match issue.severity.as_str() {
                    "Critical" => "🚨",
                    "High" => "âš ī¸",
                    "Medium" => "đŸ”ļ",
                    "Low" => "â„šī¸",
                    _ => "💡",
                };

                let severity_style = match issue.severity.as_str() {
                    "Critical" => THEME.error_style(),
                    "High" => THEME.warning_style(),
                    "Medium" => THEME.warning_style(),
                    "Low" => THEME.info_style(),
                    _ => Style::default(),
                };

                let is_selected = i == state.selected_issue;

                // Create a multi-line item for better readability
                let lines = vec![
                    Line::from(vec![
                        Span::styled(format!("{severity_icon} "), severity_style),
                        Span::styled(issue.severity.to_string(), severity_style),
                        Span::raw("  "),
                        Span::styled(format!("{}:{}", issue.file, issue.line), THEME.info_style()),
                    ]),
                    Line::from(vec![
                        Span::raw("   "),
                        Span::styled(format!("{}: ", issue.category), THEME.header_style()),
                        Span::raw(issue.description.to_string()),
                    ]),
                    Line::from(""), // Empty line for spacing
                ];

                let style = if is_selected {
                    THEME.selected_style()
                } else {
                    Style::default()
                };

                ListItem::new(lines).style(style)
            })
            .collect();

        let issue_list = List::new(items)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .title(format!(
                        "Issues ({}/{})",
                        state.selected_issue + 1,
                        review.issues.len().max(1)
                    ))
                    .title_style(THEME.header_style()),
            )
            .highlight_style(THEME.selected_style());

        WidgetRef::render_ref(&issue_list, area, buf);
    }

    fn render_status_bar(&self, area: Rect, buf: &mut Buffer, state: &AnalysisWidgetState) {
        let status_text = if state.is_analyzing {
            "Analysis in progress... Please wait"
        } else if state.review.is_some() {
            "Use ↑↓ to navigate issues, R for reports, Esc to go back"
        } else {
            "Enter to start analysis, Esc to go back"
        };

        let status = Paragraph::new(status_text)
            .style(THEME.info_style())
            .alignment(Alignment::Center)
            .block(
                Block::default()
                    .borders(Borders::TOP)
                    .border_style(THEME.info_style()),
            );

        status.render_ref(area, buf);
    }
}