cargo-quality 0.2.0

Professional Rust code quality analysis tool with hardcoded standards
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
// SPDX-FileCopyrightText: 2025 RAprogramm <andrey.rozanov.vl@gmail.com>
// SPDX-License-Identifier: MIT

//! Report formatting for analysis results.
//!
//! Provides structured output of quality issues found during analysis,
//! grouping results by analyzer and file.

use std::{collections::HashMap, fmt};

use console::measure_text_width;
use owo_colors::OwoColorize;
use terminal_size::{Width, terminal_size};

use crate::analyzer::AnalysisResult;

/// Minimum space between columns in grid layout.
const COLUMN_GAP: usize = 4;

/// Minimum width for an analyzer column.
const MIN_ANALYZER_WIDTH: usize = 40;

/// Maximum width for an analyzer column to enable multi-column layout.
const MAX_ANALYZER_WIDTH: usize = 80;

/// Rendered analyzer block for grid layout.
struct RenderedAnalyzer {
    lines: Vec<String>,
    width: usize
}

/// Renders a single analyzer block with issues.
fn render_analyzer_block(
    analyzer_name: &str,
    message_map: &HashMap<String, Vec<(String, Vec<usize>)>>,
    color: bool
) -> RenderedAnalyzer {
    let mut content_lines = Vec::new();
    let mut max_width = MIN_ANALYZER_WIDTH;

    let total_issues: usize = message_map
        .values()
        .map(|files| files.iter().map(|(_, lines)| lines.len()).sum::<usize>())
        .sum();

    let header = if color {
        format!(
            "[{}] - {} issues",
            analyzer_name.yellow().bold(),
            total_issues.to_string().cyan()
        )
    } else {
        format!("[{}] - {} issues", analyzer_name, total_issues)
    };

    max_width = max_width.max(measure_text_width(&header));
    content_lines.push(header);

    for (message, file_list) in message_map {
        let msg_line = format!("  {}", message);
        max_width = max_width.max(measure_text_width(&msg_line));
        content_lines.push(msg_line);
        content_lines.push(String::new());

        for (file_path, mut file_lines) in file_list.iter().map(|(f, l)| (f, l.clone())) {
            file_lines.sort_unstable();

            let file_line = if color {
                format!("  {} → Lines: ", file_path.blue())
            } else {
                format!("  {} → Lines: ", file_path)
            };

            let lines_str: Vec<String> = file_lines.iter().map(|l| l.to_string()).collect();
            let joined = if color {
                lines_str
                    .iter()
                    .map(|l| format!("{}", l.magenta()))
                    .collect::<Vec<_>>()
                    .join(", ")
            } else {
                lines_str.join(", ")
            };

            if joined.len() > 60 {
                let mut line_chunks = Vec::new();
                let mut current_line = String::new();

                for (i, line_num) in lines_str.iter().enumerate() {
                    let separator = if i == 0 { "" } else { ", " };
                    let addition = if color {
                        format!("{}{}", separator, line_num.magenta())
                    } else {
                        format!("{}{}", separator, line_num)
                    };

                    let addition_len = separator.len() + line_num.len();

                    if current_line.len() + addition_len > 60 && !current_line.is_empty() {
                        line_chunks.push(current_line.clone());
                        current_line = if color {
                            format!("{}", line_num.magenta())
                        } else {
                            line_num.clone()
                        };
                    } else {
                        current_line.push_str(&addition);
                    }
                }

                if !current_line.is_empty() {
                    line_chunks.push(current_line);
                }

                for (i, chunk) in line_chunks.iter().enumerate() {
                    let full_line = if i == 0 {
                        format!("{}{}", file_line, chunk)
                    } else {
                        format!("  {} {}", " ".repeat(file_path.len() + 9), chunk)
                    };
                    max_width = max_width.max(measure_text_width(&full_line));
                    content_lines.push(full_line);
                }
            } else {
                let full_line = format!("{}{}", file_line, joined);
                max_width = max_width.max(measure_text_width(&full_line));
                content_lines.push(full_line);
            }
        }

        content_lines.push(String::new());
    }

    let final_width = max_width.clamp(MIN_ANALYZER_WIDTH, MAX_ANALYZER_WIDTH);
    let separator = "".repeat(final_width);
    let footer = "".repeat(final_width);

    let mut lines = Vec::with_capacity(content_lines.len() + 2);
    lines.push(content_lines[0].clone());
    lines.push(if color {
        separator.dimmed().to_string()
    } else {
        separator
    });

    for line in &content_lines[1..] {
        let line_width = measure_text_width(line);
        if line_width > final_width {
            let mut truncated = line.clone();
            while measure_text_width(&truncated) > final_width - 3 {
                truncated.pop();
            }
            truncated.push_str("...");
            lines.push(truncated);
        } else {
            lines.push(line.clone());
        }
    }

    lines.push(if color {
        footer.dimmed().to_string()
    } else {
        footer
    });

    RenderedAnalyzer {
        lines,
        width: final_width
    }
}

/// Calculate optimal number of columns for grid layout.
fn calculate_columns(analyzers: &[RenderedAnalyzer], term_width: usize) -> usize {
    if analyzers.is_empty() {
        return 1;
    }

    let max_analyzer_width = analyzers
        .iter()
        .map(|a| a.width)
        .max()
        .unwrap_or(MIN_ANALYZER_WIDTH)
        .max(MIN_ANALYZER_WIDTH);

    for cols in (1..=analyzers.len()).rev() {
        let total_width = cols * max_analyzer_width + (cols.saturating_sub(1)) * COLUMN_GAP;

        if total_width <= term_width {
            return cols;
        }
    }

    1
}

/// Renders analyzers in grid layout.
fn render_grid(analyzers: &[RenderedAnalyzer], columns: usize) -> String {
    let mut output = String::new();

    if analyzers.is_empty() {
        return output;
    }

    if columns == 1 {
        for analyzer in analyzers {
            for line in &analyzer.lines {
                output.push_str(line);
                output.push('\n');
            }
            output.push('\n');
        }
        return output;
    }

    let col_width = analyzers
        .iter()
        .map(|a| a.width)
        .max()
        .unwrap_or(MIN_ANALYZER_WIDTH);

    for chunk in analyzers.chunks(columns) {
        let max_lines = chunk.iter().map(|a| a.lines.len()).max().unwrap_or(0);

        for row_idx in 0..max_lines {
            let mut row_output = String::with_capacity(columns * (col_width + COLUMN_GAP));

            for (col_idx, analyzer) in chunk.iter().enumerate() {
                let line = analyzer
                    .lines
                    .get(row_idx)
                    .map(String::as_str)
                    .unwrap_or("");

                let visual_width = measure_text_width(line);
                let padding = col_width.saturating_sub(visual_width);

                row_output.push_str(line);
                row_output.push_str(&" ".repeat(padding));

                if col_idx < chunk.len() - 1 {
                    row_output.push_str(&" ".repeat(COLUMN_GAP));
                }
            }

            output.push_str(&row_output);
            output.push('\n');
        }

        output.push('\n');
    }

    output
}

/// Report formatter for analysis results.
///
/// Aggregates results from multiple analyzers for a single file and
/// provides formatted output with issue counts and suggestions.
pub struct Report {
    /// File path being analyzed
    pub file_path: String,
    /// Analysis results grouped by analyzer name
    pub results:   Vec<(String, AnalysisResult)>
}

impl Report {
    /// Create new report for a file.
    ///
    /// # Arguments
    ///
    /// * `file_path` - Path to file being analyzed
    ///
    /// # Returns
    ///
    /// Empty report ready to accumulate results
    pub fn new(file_path: String) -> Self {
        Self {
            file_path,
            results: Vec::new()
        }
    }

    /// Add analysis result from an analyzer.
    ///
    /// # Arguments
    ///
    /// * `analyzer_name` - Name of analyzer that produced results
    /// * `result` - Analysis result to add
    pub fn add_result(&mut self, analyzer_name: String, result: AnalysisResult) {
        self.results.push((analyzer_name, result));
    }

    /// Calculate total issues across all analyzers.
    ///
    /// # Returns
    ///
    /// Sum of all issues found
    pub fn total_issues(&self) -> usize {
        self.results.iter().map(|(_, r)| r.issues.len()).sum()
    }

    /// Calculate total fixable issues across all analyzers.
    ///
    /// # Returns
    ///
    /// Sum of all fixable issues
    pub fn total_fixable(&self) -> usize {
        self.results.iter().map(|(_, r)| r.fixable_count).sum()
    }
}

impl fmt::Display for Report {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "Quality report for: {}", self.file_path)?;
        writeln!(f, "=")?;

        for (analyzer_name, result) in &self.results {
            if result.issues.is_empty() {
                continue;
            }

            writeln!(f, "\n[{}]", analyzer_name)?;
            for issue in &result.issues {
                write!(f, "  {}:{} - {}", issue.line, issue.column, issue.message)?;
                if issue.fix.is_available() {
                    if let Some((import, _pattern, _replacement)) = issue.fix.as_import() {
                        write!(f, "\n    Fix: Add import: {}", import)?;
                        write!(f, "\n    (Will replace path with short name)")?;
                    } else if let Some(simple) = issue.fix.as_simple() {
                        write!(f, "\n    Fix: {}", simple)?;
                    }
                }
                writeln!(f)?;
            }
        }

        writeln!(f, "\nTotal issues: {}", self.total_issues())?;
        writeln!(f, "Fixable: {}", self.total_fixable())?;

        Ok(())
    }
}

/// Global report aggregator across multiple files.
///
/// Collects reports from multiple files and provides globally grouped output.
pub struct GlobalReport {
    /// Collection of per-file reports
    pub reports: Vec<Report>
}

impl GlobalReport {
    /// Create new global report.
    pub fn new() -> Self {
        Self {
            reports: Vec::new()
        }
    }

    /// Add a file report to the global collection.
    pub fn add_report(&mut self, report: Report) {
        self.reports.push(report);
    }

    /// Calculate total issues across all files.
    pub fn total_issues(&self) -> usize {
        self.reports.iter().map(|r| r.total_issues()).sum()
    }

    /// Calculate total fixable issues across all files.
    pub fn total_fixable(&self) -> usize {
        self.reports.iter().map(|r| r.total_fixable()).sum()
    }

    /// Display summary only (total issues and fixable count).
    pub fn display_compact(&self, color: bool) -> String {
        let mut output = String::new();

        if color {
            output.push_str(&format!(
                "{}: {}\n",
                "Total issues".green().bold(),
                self.total_issues().to_string().green().bold()
            ));
            output.push_str(&format!(
                "{}: {}\n",
                "Fixable".green().bold(),
                self.total_fixable().to_string().green().bold()
            ));
        } else {
            output.push_str(&format!("Total issues: {}\n", self.total_issues()));
            output.push_str(&format!("Fixable: {}\n", self.total_fixable()));
        }

        output
    }

    /// Display details for a specific analyzer only.
    pub fn display_analyzer(&self, analyzer_name: &str, color: bool) -> String {
        type FileLines = Vec<(String, Vec<usize>)>;
        type MessageGroups = HashMap<String, FileLines>;

        let mut message_map: MessageGroups = HashMap::new();

        for report in &self.reports {
            for (name, result) in &report.results {
                if name != analyzer_name || result.issues.is_empty() {
                    continue;
                }

                for issue in &result.issues {
                    let file_list = message_map.entry(issue.message.clone()).or_default();

                    if let Some((_, lines)) =
                        file_list.iter_mut().find(|(f, _)| f == &report.file_path)
                    {
                        lines.push(issue.line);
                    } else {
                        file_list.push((report.file_path.clone(), vec![issue.line]));
                    }
                }
            }
        }

        if message_map.is_empty() {
            return String::new();
        }

        let rendered = render_analyzer_block(analyzer_name, &message_map, color);
        let mut output = String::new();

        for line in &rendered.lines {
            output.push_str(line);
            output.push('\n');
        }

        output.push('\n');

        if color {
            output.push_str(&format!(
                "{}: {}\n",
                "Total issues".green().bold(),
                self.total_issues().to_string().green().bold()
            ));
            output.push_str(&format!(
                "{}: {}\n",
                "Fixable".green().bold(),
                self.total_fixable().to_string().green().bold()
            ));
        } else {
            output.push_str(&format!("Total issues: {}\n", self.total_issues()));
            output.push_str(&format!("Fixable: {}\n", self.total_fixable()));
        }

        output
    }

    /// Display detailed report with grid layout (verbose mode).
    ///
    /// Groups issues by analyzer and message across all files,
    /// then shows which files have each issue in grid layout.
    pub fn display_verbose(&self, color: bool) -> String {
        type FileLines = Vec<(String, Vec<usize>)>;
        type MessageGroups = HashMap<String, FileLines>;
        type AnalyzerGroups = HashMap<String, MessageGroups>;

        let mut analyzer_groups: AnalyzerGroups = HashMap::new();

        for report in &self.reports {
            for (analyzer_name, result) in &report.results {
                if result.issues.is_empty() {
                    continue;
                }

                let message_map = analyzer_groups.entry(analyzer_name.clone()).or_default();

                for issue in &result.issues {
                    let file_list = message_map.entry(issue.message.clone()).or_default();

                    if let Some((_, lines)) =
                        file_list.iter_mut().find(|(f, _)| f == &report.file_path)
                    {
                        lines.push(issue.line);
                    } else {
                        file_list.push((report.file_path.clone(), vec![issue.line]));
                    }
                }
            }
        }

        let mut analyzer_names: Vec<_> = analyzer_groups.keys().cloned().collect();
        analyzer_names.sort();

        let rendered_analyzers: Vec<RenderedAnalyzer> = analyzer_names
            .iter()
            .map(|name| {
                let message_map = &analyzer_groups[name];
                render_analyzer_block(name, message_map, color)
            })
            .collect();

        let term_width = terminal_size()
            .map(|(Width(w), _)| w as usize)
            .unwrap_or(170);

        let columns = calculate_columns(&rendered_analyzers, term_width);

        let mut output = render_grid(&rendered_analyzers, columns);

        if color {
            output.push_str(&format!(
                "\n{}: {}\n",
                "Total issues".green().bold(),
                self.total_issues().to_string().green().bold()
            ));
            output.push_str(&format!(
                "{}: {}\n",
                "Fixable".green().bold(),
                self.total_fixable().to_string().green().bold()
            ));
        } else {
            output.push_str(&format!("\nTotal issues: {}\n", self.total_issues()));
            output.push_str(&format!("Fixable: {}\n", self.total_fixable()));
        }

        output
    }
}

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

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

    #[test]
    fn test_report_creation() {
        let report = Report::new("test.rs".to_string());
        assert_eq!(report.file_path, "test.rs");
        assert_eq!(report.results.len(), 0);
    }

    #[test]
    fn test_report_add_result() {
        let mut report = Report::new("test.rs".to_string());
        let result = AnalysisResult {
            issues:        vec![],
            fixable_count: 0
        };

        report.add_result("test_analyzer".to_string(), result);
        assert_eq!(report.results.len(), 1);
    }

    #[test]
    fn test_report_total_issues() {
        let mut report = Report::new("test.rs".to_string());

        let issue = Issue {
            line:    1,
            column:  1,
            message: "Test".to_string(),
            fix:     crate::analyzer::Fix::None
        };

        let result = AnalysisResult {
            issues:        vec![issue],
            fixable_count: 1
        };

        report.add_result("analyzer1".to_string(), result);
        assert_eq!(report.total_issues(), 1);
        assert_eq!(report.total_fixable(), 1);
    }

    #[test]
    fn test_report_display_with_issues() {
        let mut report = Report::new("test.rs".to_string());

        let issue = Issue {
            line:    42,
            column:  15,
            message: "Test issue".to_string(),
            fix:     crate::analyzer::Fix::Simple("Fix suggestion".to_string())
        };

        let result = AnalysisResult {
            issues:        vec![issue],
            fixable_count: 1
        };

        report.add_result("test_analyzer".to_string(), result);

        let output = format!("{}", report);
        assert!(output.contains("Quality report for: test.rs"));
        assert!(output.contains("test_analyzer"));
        assert!(output.contains("42:15 - Test issue"));
        assert!(output.contains("Fix: Fix suggestion"));
        assert!(output.contains("Total issues: 1"));
        assert!(output.contains("Fixable: 1"));
    }

    #[test]
    fn test_report_display_without_issues() {
        let mut report = Report::new("test.rs".to_string());

        let result = AnalysisResult {
            issues:        vec![],
            fixable_count: 0
        };

        report.add_result("empty_analyzer".to_string(), result);

        let output = format!("{}", report);
        assert!(output.contains("Quality report for: test.rs"));
        assert!(!output.contains("empty_analyzer"));
        assert!(output.contains("Total issues: 0"));
        assert!(output.contains("Fixable: 0"));
    }

    #[test]
    fn test_report_display_issue_without_suggestion() {
        let mut report = Report::new("file.rs".to_string());

        let issue = Issue {
            line:    10,
            column:  5,
            message: "Warning message".to_string(),
            fix:     crate::analyzer::Fix::None
        };

        let result = AnalysisResult {
            issues:        vec![issue],
            fixable_count: 0
        };

        report.add_result("warn_analyzer".to_string(), result);

        let output = format!("{}", report);
        assert!(output.contains("10:5 - Warning message"));
        assert!(!output.contains("Fix:"));
    }

    #[test]
    fn test_report_multiple_analyzers() {
        let mut report = Report::new("code.rs".to_string());

        let issue1 = Issue {
            line:    1,
            column:  1,
            message: "Issue 1".to_string(),
            fix:     crate::analyzer::Fix::Simple("Fix 1".to_string())
        };

        let issue2 = Issue {
            line:    2,
            column:  2,
            message: "Issue 2".to_string(),
            fix:     crate::analyzer::Fix::None
        };

        report.add_result(
            "analyzer1".to_string(),
            AnalysisResult {
                issues:        vec![issue1],
                fixable_count: 1
            }
        );

        report.add_result(
            "analyzer2".to_string(),
            AnalysisResult {
                issues:        vec![issue2],
                fixable_count: 0
            }
        );

        assert_eq!(report.total_issues(), 2);
        assert_eq!(report.total_fixable(), 1);

        let output = format!("{}", report);
        assert!(output.contains("analyzer1"));
        assert!(output.contains("analyzer2"));
        assert!(output.contains("Total issues: 2"));
    }

    #[test]
    fn test_report_total_fixable() {
        let mut report = Report::new("test.rs".to_string());

        report.add_result(
            "analyzer1".to_string(),
            AnalysisResult {
                issues:        vec![],
                fixable_count: 3
            }
        );

        report.add_result(
            "analyzer2".to_string(),
            AnalysisResult {
                issues:        vec![],
                fixable_count: 2
            }
        );

        assert_eq!(report.total_fixable(), 5);
    }
}