codesniff 0.1.2

Simple CLI tool to explore codebases looking for code smells.
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 regex::RegexBuilder;
use std::collections::HashMap;
use std::path::Path;
use std::process::Command;
use std::{
    error::Error,
    io,
    time::{Duration, Instant},
};

mod stateful;
mod viewer;
use crate::stateful::StatefulList;
use crate::viewer::Viewer;
use crossterm::{
    event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{prelude::*, widgets::*};

#[allow(unused_macros)]
macro_rules! log {
    ($e: expr) => {
        use ::std::io::Write;
        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .append(true)
            .open("log.txt")
            .unwrap();

        writeln!(file, $e).unwrap()
    };
}

#[derive(Debug)]
#[allow(dead_code)]
struct Commit {
    sha: String,
    title: String,
    files: Vec<String>,
}

enum State {
    Searching,
    Files,
    View,
}

struct GlobalState {
    commits: Vec<Commit>,
    file: Option<(String, String, String)>,
}

impl GlobalState {
    pub fn new(commits: Vec<Commit>) -> Self {
        Self {
            commits,
            file: None,
        }
    }
}

/// This struct holds the current state of the app. In particular, it has the `items` field which is
/// a wrapper around `ListState`. Keeping track of the items state let us render the associated
/// widget with its state and have access to features such as natural scrolling.
///
/// Check the event handling at the bottom to see how to change the state on incoming events.
/// Check the drawing logic for items on how to specify the highlighting style for selected items.
struct App<'a> {
    items: StatefulList<Modified<'a>>,
    search: String,
    state: State,
}

impl<'a> App<'a> {
    fn new(commits: &'a [Commit]) -> Self {
        let most_modified = most_modified(commits.iter());
        let items = StatefulList::with_items(most_modified);
        let search = String::new();
        let state = State::Files;
        Self {
            items,
            search,
            state,
        }
    }

    fn update_filtered(&mut self, commits: &'a [Commit]) {
        let most_modified = if let Ok(search) = RegexBuilder::new(&self.search)
            .case_insensitive(true)
            .build()
        {
            let filtered_commits = commits.iter().filter_map(|commit| {
                if search.is_match(&commit.title) {
                    Some(commit)
                } else {
                    None
                }
            });
            most_modified(filtered_commits)
        } else {
            // TODO search
            most_modified(commits.iter())
        };
        let items = StatefulList::with_items(most_modified);
        self.items = items;
    }

    // /// Rotate through the event list.
    // /// This only exists to simulate some kind of "progress"
    // fn on_tick(&mut self) {
    //     let event = self.events.remove(0);
    //     self.events.push(event);
    // }
}
enum ParseState {
    Sha,
    Title,
    Files,
}

fn parse(output: String) -> Vec<Commit> {
    let mut commits = vec![];

    let mut state = ParseState::Sha;
    let mut current_sha = "".to_string();
    let mut current_title = "".to_string();
    let mut current_files = vec![];
    for line in output.lines() {
        let line = line.trim().to_string();
        match state {
            ParseState::Sha => {
                current_sha = line;
                state = ParseState::Title;
            }
            ParseState::Title => {
                if line.is_empty() {
                    state = ParseState::Files;
                } else {
                    current_title = line;
                }
            }
            ParseState::Files => {
                if line.is_empty() {
                    if !current_files.is_empty() {
                        let commit = Commit {
                            sha: current_sha.clone(),
                            title: current_title.clone(),
                            files: current_files.clone(),
                        };
                        commits.push(commit);
                        current_files.clear();
                        state = ParseState::Sha;
                    }
                } else {
                    current_files.push(line);
                }
            }
        }
    }
    let commit = Commit {
        sha: current_sha.clone(),
        title: current_title.clone(),
        files: current_files.clone(),
    };
    commits.push(commit);
    commits
}

struct Modified<'a> {
    file: &'a String,
    commits: Vec<&'a Commit>,
}
fn most_modified<'a, I: Iterator<Item = &'a Commit>>(commits: I) -> Vec<Modified<'a>> {
    let mut map = HashMap::new();
    for commit in commits {
        for file in &commit.files {
            let path = Path::new(file);
            if path.exists() {
                map.entry(file).or_insert(vec![]).push(commit);
            }
        }
    }
    let mut vec: Vec<_> = map.into_iter().collect();
    vec.sort_by(|(_, a), (_, b)| b.len().cmp(&a.len()));
    vec.into_iter()
        .map(|(file, commits)| Modified { file, commits })
        .collect()
}

fn main() -> Result<(), Box<dyn Error>> {
    // setup terminal
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    // create app and run it
    let tick_rate = Duration::from_millis(250);
    let output = Command::new("git")
        .args(["log", "--pretty=%n%h%n%s%n", "--name-only"])
        .output()
        .expect(
            "`git` is required to run `codesniff`. Install it and make it available in your path",
        );
    let output = String::from_utf8(output.stdout).expect(" Expected valid utf-8");
    let commits = parse(output);
    let res = run_app(&mut terminal, commits, tick_rate);

    // restore terminal
    disable_raw_mode()?;
    execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture
    )?;
    terminal.show_cursor()?;

    if let Err(err) = res {
        println!("{err:?}");
    }

    Ok(())
}

fn ui<B: Backend>(f: &mut Frame<B>, app: &mut App, viewer: &mut Option<Viewer>) {
    if let Some(viewer) = viewer {
        viewer.render(f);
    } else {
        // Create two chunks with equal horizontal screen space
        let main = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Length(3), Constraint::Min(10)].as_ref())
            .split(f.size());

        let search = Span::raw(app.search.clone());
        // Create a List from all list items and highlight the currently selected one
        let color = if let State::Searching = app.state {
            Color::Red
        } else {
            Color::White
        };
        let search = List::new(vec![ListItem::new(search)]).block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(Style::default().fg(color))
                .title("Filter commit"),
        );
        f.render_widget(search, main[0]);

        let chunks = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Min(10), Constraint::Length(4)].as_ref())
            .split(main[1]);

        // Iterate through all elements in the `items` app and append some debug text to it.
        let width = f.size().width as usize;

        let mut max_value = 0;
        let items: Vec<ListItem> = app
            .items
            .items
            .iter()
            .map(|Modified { file, commits }| {
                let count = commits.len();
                max_value = std::cmp::max(count, max_value);
                let lines = vec![Line::from(vec![
                    // 8 = 2 * 1 border + ??
                    format!("{: <1$}", file, width - 12).into(),
                    " ".into(),
                    format!("{: >4}", count).into(),
                ])];
                ListItem::new(lines).style(Style::default())
            })
            .collect();

        // Create a List from all list items and highlight the currently selected one
        let items = List::new(items)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .title("Modified Files"),
            )
            .highlight_style(
                Style::default()
                    // .bg(Color::LightGreen)
                    .add_modifier(Modifier::BOLD),
            );
        //.highlight_symbol(">> ");

        // We can now render the item list
        f.render_stateful_widget(items, chunks[0], &mut app.items.state);

        let heatmap: Vec<ListItem> = app
            .items
            .items
            .iter()
            .map(|Modified { commits, .. }| {
                let count = commits.len();
                let line = Line::from(vec![" ".into()]);

                let color = if max_value > 0 {
                    Color::Rgb((count * 255 / max_value) as u8, 0, 0)
                } else {
                    Color::Rgb(0, 0, 0)
                };
                ListItem::new(line).style(Style::default().bg(color))
            })
            .collect();
        let heatmap = List::new(heatmap)
            .block(Block::default().borders(Borders::ALL).title("Heat"))
            .highlight_style(Style::default());

        f.render_stateful_widget(heatmap, chunks[1], &mut app.items.state);
    }
}

fn run_app<B: Backend>(
    terminal: &mut Terminal<B>,
    commits: Vec<Commit>,
    tick_rate: Duration,
) -> io::Result<()> {
    let mut global_state = GlobalState::new(commits);
    let mut app = App::new(&global_state.commits);
    let mut viewer = None;
    let mut last_tick = Instant::now();
    loop {
        terminal.draw(|f| ui(f, &mut app, &mut viewer))?;

        let timeout = tick_rate
            .checked_sub(last_tick.elapsed())
            .unwrap_or_else(|| Duration::from_secs(0));
        if crossterm::event::poll(timeout)? {
            if let Event::Key(key) = event::read()? {
                if key.kind == KeyEventKind::Press {
                    match &mut app.state {
                        State::Searching => match key.code {
                            KeyCode::Char(x) => {
                                app.search.push(x);
                                app.update_filtered(&global_state.commits);
                            }
                            KeyCode::Backspace => {
                                app.search.pop();
                                app.update_filtered(&global_state.commits);
                            }
                            KeyCode::Esc | KeyCode::Enter => {
                                app.state = State::Files;
                            }
                            _ => {}
                        },
                        State::Files => match key.code {
                            KeyCode::Esc | KeyCode::Char('q') => return Ok(()),
                            KeyCode::Left => app.items.unselect(),
                            KeyCode::Right | KeyCode::Enter => {
                                let i = app.items.state.selected().unwrap();
                                let file = app.items.items[i].file;
                                let content = std::fs::read_to_string(&file).unwrap();
                                let output = Command::new("git")
        .args(["log", "-p", "--follow", file.as_str()])
        .output()
        .expect(
            "`git` is required to run `codesniff`. Install it and make it available in your path",
        );
                                let gitlog = String::from_utf8(output.stdout)
                                    .expect(" Expected valid utf-8");
                                global_state.file = Some((file.clone(), content, gitlog));

                                let (file, content, gitlog) = &global_state.file.as_ref().unwrap();

                                viewer = Some(Viewer::new(file, content, gitlog));
                                app.state = State::View;

                                // let state =
                                //     State::View(Box::new());
                                // app.state = state;
                            }
                            KeyCode::Up => app.items.previous(),
                            KeyCode::Down => app.items.next(),
                            KeyCode::Char('/') => {
                                app.state = State::Searching;
                            }
                            _ => {}
                        },
                        State::View => match key.code {
                            KeyCode::Esc | KeyCode::Char('q') => app.state = State::Files,
                            // KeyCode::Left => file.items.unselect(),
                            k => {
                                if let Some(viewer) = &mut viewer {
                                    viewer.handle_key(k)
                                }
                            }
                        },
                    }
                }
            }
        }
        if last_tick.elapsed() >= tick_rate {
            // app.on_tick();
            last_tick = Instant::now();
        }
    }
}