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
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
use crate::stateful::StatefulList;
use crossterm::event::KeyCode;
use ratatui::{prelude::*, widgets::*};
use std::collections::{HashMap, HashSet};
use std::ops::Range;

enum ParseState {
    Commit,
    Author,
    Date,
    Message,
    Diff,
}

fn parse_block(line: &str) -> (usize, usize, usize, usize) {
    let tokens: Vec<_> = line.split(" ").collect();
    let begin = tokens[1];
    let end = tokens[2];

    // [1..] to remove `-`
    let btokens: Vec<_> = begin[1..].split(",").collect();
    let begin_from = btokens[0].parse().unwrap();
    let begin_len: usize = btokens[1].parse().unwrap_or(0);

    // [1..] to remove `+`
    let etokens: Vec<_> = end[1..].split(",").collect();
    let end_from = etokens[0].parse().unwrap();
    let end_len: usize = etokens[1].parse().unwrap_or(0);
    (
        begin_from,
        begin_from + begin_len,
        end_from,
        end_from + end_len,
    )
}

#[derive(Debug)]
struct LineState<'a> {
    blocks: Vec<(Range<usize>, Range<usize>)>,
    oldblocks: Vec<(Range<usize>, Range<usize>)>,
    // line_map: HashMap<usize, i64>,
    // current_line: usize,
    commit: &'a str,
}

impl<'a> LineState<'a> {
    fn new() -> Self {
        Self {
            blocks: vec![],
            oldblocks: vec![],
            // current_line: 0,
            // line_map: HashMap::new(),
            commit: "",
        }
    }

    fn fuse_blocks(&self) -> Vec<(Range<usize>, Range<usize>)> {
        if self.oldblocks.is_empty() {
            self.blocks.clone()
        } else {
            let mut new_blocks = vec![];
            for (before, after) in &self.blocks {
                let mut offset: i64 = 0;
                for (before_original, original) in &self.oldblocks {
                    if after.end < before_original.start {
                        // offset += (after.end - after.start) - (before.end - before.start);
                        offset += (original.end - original.start) as i64
                            - (before_original.end - before_original.start) as i64;
                        continue;
                    } else if after.start > before.end {
                        break;
                    } else {
                        let original_start = if after.start > before_original.start {
                            original
                                .start
                                .saturating_sub(after.start - before_original.start)
                        } else {
                            before.start + before_original.start - after.start
                        };
                        let original_end = if after.end > before_original.end {
                            original.end + after.end - before_original.end
                        } else {
                            before.end - (before_original.end - after.end)
                        };

                        // OFFSET
                        let original_start: usize =
                            (original_start as i64 + offset).try_into().unwrap();
                        let original_end: usize =
                            (original_end as i64 + offset).try_into().unwrap();

                        if original_end == original_start {
                            continue;
                        } else {
                            new_blocks.push((before.clone(), original_start..original_end));
                            break;
                        }
                    }
                }
            }
            new_blocks
        }
    }

    fn update_map<'b>(&mut self, map: &'b mut HashMap<usize, HashSet<&'a str>>) {
        let blocks = self.fuse_blocks();
        for (_before, after) in &blocks {
            for current_line in after.clone() {
                map.entry(current_line)
                    .or_insert(HashSet::new())
                    .insert(self.commit);
            }
        }
        self.oldblocks = blocks;
        self.blocks.clear();
    }
}

fn update_diff_state<'a>(
    line: &'a str,
    state: &mut LineState<'a>,
    // map: &mut HashMap<usize, HashSet<&'a str>>,
) {
    if line.starts_with("@@") {
        let (end_from, end_to, begin_from, begin_to) = parse_block(line);
        state.blocks.push((end_from..end_to, begin_from..begin_to));
    }
}

fn parse(output: &str) -> HashMap<usize, HashSet<&str>> {
    let mut state = ParseState::Commit;
    let mut map = HashMap::new();
    let mut line_state = LineState::new();
    for line in output.lines() {
        match state {
            ParseState::Commit => {
                assert!(line.starts_with("commit "));
                line_state.commit = &line["commit ".len()..];
                state = ParseState::Author;
            }
            ParseState::Author => {
                assert!(line.starts_with("Author: "));
                // TODO do something here ?
                state = ParseState::Date;
            }
            ParseState::Date => {
                assert!(line.starts_with("Date: "));
                state = ParseState::Message;
            }
            ParseState::Message => {
                if line.starts_with("diff ") {
                    state = ParseState::Diff;
                }
            }
            ParseState::Diff => {
                if line.is_empty() {
                    state = ParseState::Commit;
                    line_state.update_map(&mut map);
                } else {
                    update_diff_state(line, &mut line_state);
                }
            }
        }
    }
    if let ParseState::Diff = state {
        line_state.update_map(&mut map);
    }
    map
}

pub struct Viewer<'a> {
    file: &'a str,
    items: StatefulList<(&'a str, usize)>,
}

impl<'a> Viewer<'a> {
    pub fn new(file: &'a str, content: &'a str, gitlog: &'a str) -> Self {
        let lines: Vec<&str> = content.lines().collect();
        let commits = parse(&gitlog);
        let lines = lines
            .into_iter()
            .enumerate()
            .map(|(i, line)| {
                (
                    line,
                    commits.get(&i).map(|commits| commits.len()).unwrap_or(0),
                )
            })
            .collect();
        let items = StatefulList::with_items(lines);
        Self { file, items }
    }

    pub fn handle_key(&mut self, key: KeyCode) {
        match key {
            KeyCode::Up => self.items.previous(),
            KeyCode::Down => self.items.next(),
            KeyCode::PageUp => self.items.previous_nth(20),
            KeyCode::PageDown => self.items.next_nth(20),
            _ => {}
        }
    }
    pub fn render<B: Backend>(&mut self, f: &mut Frame<B>) {
        let chunks = Layout::default()
            .direction(Direction::Horizontal)
            .constraints(
                [
                    Constraint::Min(10),
                    Constraint::Length(4),
                    Constraint::Length(4),
                ]
                .as_ref(),
            )
            .split(f.size());
        let mut max_value = 0;
        let items: Vec<ListItem> = self
            .items
            .items
            .iter()
            .map(|(line, count)| {
                max_value = std::cmp::max(*count, max_value);
                ListItem::new(Line::from(line.to_string())).style(Style::default())
            })
            .collect();

        // Create a List from all list items and highlight the currently selected one
        let title: &str = self.file;
        let items = List::new(items)
            .block(Block::default().borders(Borders::ALL).title(title))
            .highlight_style(Style::default().add_modifier(Modifier::BOLD));

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

        let heatmap: Vec<ListItem> = self
            .items
            .items
            .iter()
            .map(|(_line, count)| {
                // let line = Line::from(vec![format!("{}", count * 100 / max_value).into()]);
                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 self.items.state);

        let num_lines = self.items.items.len();
        let mut current_count = 0;
        let bucket = std::cmp::max(num_lines / (f.size().height as usize - 4), 1);
        let mut max_value = 0;
        let file_overview: Vec<_> = self
            .items
            .items
            .iter()
            .enumerate()
            .filter_map(|(line_no, (_line, count))| {
                current_count += count;
                if (line_no + 1) % bucket == 0 {
                    let count = current_count;
                    if count > max_value {
                        max_value = count;
                    }
                    current_count = 0;
                    Some((line_no + 1 - bucket, count))
                } else {
                    None
                }
            })
            .collect();
        let file_heatmap: Vec<ListItem> = file_overview
            .into_iter()
            .map(|(line_no, count)| {
                let line = Line::from(vec![" ".into()]);
                // let line = Line::from(vec![format!("{}", count * 100 / max_value).into()]);

                let color = match (self.items.state.selected(), max_value) {
                    (Some(selected), _) if selected > line_no && selected < line_no + bucket => {
                        Color::Rgb(0, 0, 255)
                    }
                    (_, max_value) if max_value > 0 => {
                        Color::Rgb((count * 255 / max_value) as u8, 0, 0)
                    }
                    _ => Color::Rgb(0, 0, 0),
                };

                ListItem::new(line).style(Style::default().bg(color))
            })
            .collect();
        let file_heatmap = List::new(file_heatmap)
            .block(Block::default().borders(Borders::ALL).title("File heat"))
            .highlight_style(Style::default());

        f.render_widget(file_heatmap, chunks[2]);
    }
}

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

    const NEW_FILE: &'static str = r#"commit 549f59a7bf0c348b17ce682725b822f02e8122d2
Author: Nicolas Patry <patry.nicolas@protonmail.com>
Date:   Sun Aug 20 18:27:43 2023 +0200

Title


diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644
index 0000000..2ae0fef
--- /dev/null
+++ b/Cargo.toml
@@ -0,0 +1,2 @@
+[package]
+name = "codesniff"
"#;

    const LINE_FOLLOW: &'static str = r#"commit 549f59a7bf0c348b17ce682725b822f02e8122d2
Author: Nicolas Patry <patry.nicolas@protonmail.com>
Date:   Sun Aug 20 18:27:43 2023 +0200

    5.

diff --git a/test/test.txt b/test/test.txt
index ec0a8fa..5be6427 100644
--- a/test/test.txt
+++ b/test/test.txt
@@ -1,3 +1,4 @@
 Line yellow: count: 1
-Line red: count: 4
-Line purple: count: 1
+Line red: count: 5
+Line purple: count: 2
+Line green: count: 1

commit 621a9685d2fa18a0a83ef820932f15f514f7ee26
Author: Nicolas Patry <patry.nicolas@protonmail.com>
Date:   Sun Aug 20 18:27:14 2023 +0200

    4.

diff --git a/test/test.txt b/test/test.txt
index bc78bac..ec0a8fa 100644
--- a/test/test.txt
+++ b/test/test.txt
@@ -1,4 +1,3 @@
-Line blue: count: 1
 Line yellow: count: 1
-Line red: count: 3
+Line red: count: 4
 Line purple: count: 1

commit 2cafab8027624c7210174a68b1c5cf0e457c4879
Author: Nicolas Patry <patry.nicolas@protonmail.com>
Date:   Sun Aug 20 18:26:53 2023 +0200

    3.

diff --git a/test/test.txt b/test/test.txt
index 9117d95..bc78bac 100644
--- a/test/test.txt
+++ b/test/test.txt
@@ -1,3 +1,4 @@
 Line blue: count: 1
-Line red: count: 2
+Line yellow: count: 1
+Line red: count: 3
 Line purple: count: 1

commit 3d48ad25815605d219dc2fd10aea12d052424a56
Author: Nicolas Patry <patry.nicolas@protonmail.com>
Date:   Sun Aug 20 18:26:28 2023 +0200

    2

diff --git a/test/test.txt b/test/test.txt
index 53d4777..9117d95 100644
--- a/test/test.txt
+++ b/test/test.txt
@@ -1,3 +1,3 @@
 Line blue: count: 1
-Line red: count: 1
+Line red: count: 2
 Line purple: count: 1

commit ba6536e2adc1eecba9d9692ec09146dfba18e394
Author: Nicolas Patry <patry.nicolas@protonmail.com>
Date:   Sun Aug 20 18:26:12 2023 +0200

    Initial commit

diff --git a/test/test.txt b/test/test.txt
new file mode 100644
index 0000000..53d4777
--- /dev/null
+++ b/test/test.txt
@@ -0,0 +1,3 @@
+Line blue: count: 1
+Line red: count: 1
+Line purple: count: 1
"#;

    #[test]
    fn test_parse_commit() {
        let map = parse(NEW_FILE);
        // assert_eq!(state.line_map, HashMap::from([(0, 8)]));
        let commit = "549f59a7bf0c348b17ce682725b822f02e8122d2";
        assert_eq!(
            map,
            HashMap::from([(1, HashSet::from([commit])), (2, HashSet::from([commit]))])
        );
    }

    #[test]
    fn test_line_follow_1() {
        let patch = LINE_FOLLOW.lines().collect::<Vec<_>>();
        let patch = &patch[patch.len() - 15..].join("\n");
        let map = parse(patch);
        let map: HashMap<_, _> = map
            .into_iter()
            .map(|(line, set)| (line, set.len()))
            .collect();
        assert_eq!(map, HashMap::from([(1, 1), (2, 1), (3, 1)]));
    }

    #[test]
    fn test_line_follow_2() {
        let map = parse(LINE_FOLLOW);
        let map: HashMap<_, _> = map
            .into_iter()
            .map(|(line, set)| (line, set.len()))
            .collect();
        assert_eq!(map, HashMap::from([(1, 4), (2, 4), (3, 4), (4, 2)]));
        // assert_eq!(map, HashMap::from([(0, HashSet::from([""]))]));
    }
}