Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 67 additions & 14 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ use ignore::WalkBuilder;
use ratatui::{backend::CrosstermBackend, Terminal};
use scanner::{Finding, Severity};
use std::fs::File;
use std::io::{self, Write};
use std::io;
use ui::FilterMode;
// use std::path::Path;

fn main() -> Result<()> {
Expand Down Expand Up @@ -362,11 +363,51 @@ fn run_app<B: ratatui::backend::Backend>(
}

match key.code {
KeyCode::Char('q') | KeyCode::Esc => return Ok(()),
KeyCode::Char('q') | KeyCode::Esc => {
if app.show_context {
app.show_context = false;
} else {
return Ok(());
}
}
KeyCode::Enter => {
if app.show_context {
app.show_context = false;
} else if let Some(sel) = app.state.selected() {
if let Some(f) = app.findings.get(sel) {
match ui::get_file_context(&f.file_path, f.line_number) {
Ok(lines) => {
app.context_lines = Some(lines);
app.show_context = true;
}
Err(e) => {
app.clipboard_status =
Some(format!("Error reading context: {}", e));
}
}
}
}
}
KeyCode::Down => app.next(),
KeyCode::Up => app.previous(),
KeyCode::Char('s') => app.strict_mode = !app.strict_mode,
KeyCode::Char('?') => app.show_help = !app.show_help,
KeyCode::Char('1') => {
app.filter_mode = FilterMode::All;
app.update_visible_findings();
}
KeyCode::Char('2') => {
app.filter_mode = FilterMode::High;
app.update_visible_findings();
}
KeyCode::Char('3') => {
app.filter_mode = FilterMode::Medium;
app.update_visible_findings();
}
KeyCode::Char('4') => {
app.filter_mode = FilterMode::Low;
app.update_visible_findings();
}
KeyCode::Char('c') => {
if let Some(sel) = app.state.selected() {
if let Some(f) = app.findings.get(sel) {
Expand Down Expand Up @@ -405,14 +446,21 @@ fn run_app<B: ratatui::backend::Backend>(
};
match fixer::fix_file(&f.file_path, vec![replacement]) {
Ok(_) => {
app.findings.remove(sel);
let fingerprint = f.fingerprint.clone();
// Remove from all_findings
if let Some(idx) = app
.all_findings
.iter()
.position(|x| x.fingerprint == fingerprint)
{
app.all_findings.remove(idx);
}
app.update_visible_findings();
app.clipboard_status = Some("Fixed!".to_string());
if app.findings.is_empty() {

if app.all_findings.is_empty() {
return Ok(());
}
if sel >= app.findings.len() {
app.state.select(Some(app.findings.len() - 1));
}
}
Err(e) => {
app.clipboard_status = Some(format!("Error: {}", e));
Expand All @@ -433,14 +481,19 @@ fn run_app<B: ratatui::backend::Backend>(
);
let _ = baseline.save();

// Remove from UI list
app.findings.remove(sel);
if app.findings.is_empty() {
return Ok(()); // All handled
let fingerprint = f.fingerprint.clone();
// Remove from all_findings
if let Some(idx) = app
.all_findings
.iter()
.position(|x| x.fingerprint == fingerprint)
{
app.all_findings.remove(idx);
}
// Adjust selection
if sel >= app.findings.len() {
app.state.select(Some(app.findings.len() - 1));
app.update_visible_findings();

if app.all_findings.is_empty() {
return Ok(()); // All handled
}
}
}
Expand Down
115 changes: 114 additions & 1 deletion src/ui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,28 @@ use ratatui::{
widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap},
Frame,
};
use std::fs::File;
use std::io::{self, BufRead, BufReader};

#[derive(Debug, PartialEq, Clone, Copy)]
pub enum FilterMode {
All,
High,
Medium,
Low,
}

pub struct App {
pub all_findings: Vec<Finding>,
pub findings: Vec<Finding>,
pub state: ListState,
pub strict_mode: bool,
pub show_help: bool,
pub _show_quit_confirm: bool,
pub clipboard_status: Option<String>,
pub filter_mode: FilterMode,
pub show_context: bool,
pub context_lines: Option<Vec<(usize, String)>>,
}

impl App {
Expand All @@ -24,12 +38,16 @@ impl App {
state.select(Some(0));
}
App {
all_findings: findings.clone(),
findings,
state,
strict_mode: strict,
show_help: false,
_show_quit_confirm: false,
clipboard_status: None,
filter_mode: FilterMode::All,
show_context: false,
context_lines: None,
}
}

Expand Down Expand Up @@ -66,6 +84,50 @@ impl App {
};
self.state.select(Some(i));
}

pub fn update_visible_findings(&mut self) {
self.findings = self
.all_findings
.iter()
.filter(|f| match self.filter_mode {
FilterMode::All => true,
FilterMode::High => f.severity == Severity::High,
FilterMode::Medium => f.severity == Severity::Medium,
FilterMode::Low => f.severity == Severity::Low,
})
.cloned()
.collect();

// Reset selection if out of bounds
if self.findings.is_empty() {
self.state.select(None);
} else {
self.state.select(Some(0));
}
}
}

pub fn get_file_context(path: &str, line_num: usize) -> io::Result<Vec<(usize, String)>> {
let file = File::open(path)?;
let reader = BufReader::new(file);

// Context window: +/- 2 lines
let start = line_num.saturating_sub(2);
let end = line_num + 2;

let mut lines = Vec::new();
for (i, line) in reader.lines().enumerate() {
let current_line = i + 1;
if current_line >= start && current_line <= end {
if let Ok(l) = line {
lines.push((current_line, l));
}
}
if current_line > end {
break;
}
}
Ok(lines)
}
Comment on lines +110 to 131

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Line read errors are silently skipped.

If a line fails to read (e.g., invalid UTF-8), it's silently omitted from the context. This could result in fewer than 5 lines displayed with no indication of why. Consider logging or including a placeholder for unreadable lines.

💡 Optional: indicate unreadable lines
         if current_line >= start && current_line <= end {
-            if let Ok(l) = line {
-                lines.push((current_line, l));
+            match line {
+                Ok(l) => lines.push((current_line, l)),
+                Err(_) => lines.push((current_line, "<unable to read line>".to_string())),
             }
         }
🤖 Prompt for AI Agents
In `@src/ui.rs` around lines 110 - 131, get_file_context currently silently skips
lines when reader.lines() yields Err (e.g., invalid UTF-8); update the loop in
get_file_context to preserve line count by pushing a placeholder entry for
unreadable lines (e.g., return (current_line, "<unreadable line>".to_string())
or similar) instead of skipping, or alternatively log the error via your logger
from inside that branch; ensure the change touches the lines enumeration/if let
Ok(l) = line block so every current_line between start and end is appended
(either the real line or the placeholder/logged error).


pub fn ui(f: &mut Frame, app: &mut App) {
Expand Down Expand Up @@ -221,15 +283,26 @@ pub fn ui(f: &mut Frame, app: &mut App) {

// --- BOTTOM BAR ---
let mode_str = if app.strict_mode { "STRICT" } else { "NORMAL" };
let filter_str = match app.filter_mode {
FilterMode::All => "ALL",
FilterMode::High => "HIGH",
FilterMode::Medium => "MED",
FilterMode::Low => "LOW",
};
let help_text =
"q:Quit | g:Baseline (Ignore) | c:Copy | r:Repair | s:Switch Mode | ?:Help | \u{2191}\u{2193}:Nav";
"q:Quit | 1-4:Filter | g:Ignore | c:Copy | r:Repair | s:Mode | Enter:Ctx | ?:Help";

let status_bar = Paragraph::new(Line::from(vec![
Span::styled(
format!(" MODE: {} ", mode_str),
Style::default().bg(Color::Blue).fg(Color::White),
),
Span::raw(" "),
Span::styled(
format!(" FILTER: {} ", filter_str),
Style::default().bg(Color::Magenta).fg(Color::White),
),
Span::raw(" "),
Span::raw(help_text),
]))
.alignment(Alignment::Center);
Expand Down Expand Up @@ -281,6 +354,46 @@ pub fn ui(f: &mut Frame, app: &mut App) {
.wrap(Wrap { trim: true });
f.render_widget(p, area);
}

if app.show_context {
if let Some(lines) = &app.context_lines {
let area = centered_rect(80, 60, f.size());
f.render_widget(Clear, area);

let context_block = Block::default()
.title(" Context View - Esc/Enter to Close ")
.borders(Borders::ALL)
.style(Style::default().bg(Color::Black));

let mut content = Vec::new();
for (num, line) in lines {
let style = if let Some(idx) = app.state.selected() {
if let Some(finding) = app.findings.get(idx) {
if *num == finding.line_number {
Style::default().fg(Color::Red).add_modifier(Modifier::BOLD)
} else {
Style::default().fg(Color::Gray)
}
} else {
Style::default().fg(Color::Gray)
}
} else {
Style::default().fg(Color::Gray)
};

content.push(Line::from(vec![
Span::styled(format!("{: >4} | ", num), style),
Span::styled(line.replace('\t', " "), style),
]));
}

let p = Paragraph::new(content)
.block(context_block)
.wrap(Wrap { trim: false }); // preserve indentation

f.render_widget(p, area);
}
}
}

fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
Expand Down