linthis 0.17.1

A fast, cross-platform multi-language linter and formatter
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
// Copyright 2024 zhlinh and linthis Project Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found at
//
// https://opensource.org/license/MIT
//
// The above copyright notice and this permission
// notice shall be included in all copies or
// substantial portions of the Software.

//! HTML report generation for linthis.

use chrono::Local;

use super::statistics::ReportStatistics;
use super::templates::{generate_bar_chart_svg, generate_trend_chart_svg, html_report_template};
use super::trends::TrendAnalysis;
use crate::utils::types::{RunResult, Severity};

/// Options for HTML report generation.
#[derive(Debug, Clone, Default)]
pub struct HtmlReportOptions {
    /// Include trend analysis section.
    pub include_trends: bool,
    /// Trend analysis data (if available).
    pub trends: Option<TrendAnalysis>,
}

/// Generate a complete HTML report from a RunResult.
pub fn generate_html_report(result: &RunResult, options: &HtmlReportOptions) -> String {
    let stats = ReportStatistics::from_run_result(result);
    let timestamp = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();

    // Generate summary section
    let summary_html = generate_summary_html(result, &stats);

    // Generate statistics section
    let statistics_html = generate_statistics_html(&stats);

    // Generate issues section
    let issues_html = generate_issues_html(result);

    // Generate trends section (if requested)
    let trends_html = if options.include_trends {
        if let Some(ref trends) = options.trends {
            generate_trends_html(trends)
        } else {
            String::new()
        }
    } else {
        String::new()
    };

    html_report_template(
        "Linthis Lint Report",
        &summary_html,
        &statistics_html,
        &issues_html,
        &trends_html,
        &timestamp,
    )
}

/// Generate the summary section HTML.
fn generate_summary_html(result: &RunResult, stats: &ReportStatistics) -> String {
    let exit_status = match result.exit_code {
        0 => r#"<span class="stat-value success">✓ Passed</span>"#,
        1 => r#"<span class="stat-value error">✗ Failed (Errors)</span>"#,
        2 => r#"<span class="stat-value error">✗ Failed (Format)</span>"#,
        3 => r#"<span class="stat-value warning">⚠ Warnings</span>"#,
        _ => r#"<span class="stat-value">Unknown</span>"#,
    };

    format!(
        r#"<div class="stats-grid">
        <div class="stat-card">
            <div class="stat-value">{total_files}</div>
            <div class="stat-label">Total Files</div>
        </div>
        <div class="stat-card">
            <div class="stat-value error">{errors}</div>
            <div class="stat-label">Errors</div>
        </div>
        <div class="stat-card">
            <div class="stat-value warning">{warnings}</div>
            <div class="stat-label">Warnings</div>
        </div>
        <div class="stat-card">
            <div class="stat-value info">{info}</div>
            <div class="stat-label">Info</div>
        </div>
        <div class="stat-card">
            <div class="stat-value success">{clean_pct:.1}%</div>
            <div class="stat-label">Clean Files</div>
        </div>
        <div class="stat-card">
            {exit_status}
            <div class="stat-label">Status</div>
        </div>
    </div>
    <p><strong>Duration:</strong> {duration}ms | <strong>Files with issues:</strong> {files_with_issues}</p>"#,
        total_files = result.total_files,
        errors = stats.severity_counts.errors,
        warnings = stats.severity_counts.warnings,
        info = stats.severity_counts.info,
        clean_pct = stats.summary.clean_file_percentage,
        exit_status = exit_status,
        duration = result.duration_ms,
        files_with_issues = result.files_with_issues,
    )
}

/// Generate the statistics section HTML.
fn generate_statistics_html(stats: &ReportStatistics) -> String {
    let mut html = String::new();

    // Issues by language chart
    if !stats.by_language.is_empty() {
        let mut lang_data: Vec<_> = stats.by_language.iter().collect();
        lang_data.sort_by(|a, b| b.1.cmp(a.1));
        let chart_data: Vec<_> = lang_data
            .into_iter()
            .take(8)
            .map(|(k, v)| (k.clone(), *v))
            .collect();
        html.push_str(&generate_bar_chart_svg(
            &chart_data,
            500,
            200,
            "Issues group by Language",
        ));
    }

    // Issues by tool chart
    if !stats.by_tool.is_empty() {
        let mut tool_data: Vec<_> = stats.by_tool.iter().collect();
        tool_data.sort_by(|a, b| b.1.cmp(a.1));
        let chart_data: Vec<_> = tool_data
            .into_iter()
            .take(8)
            .map(|(k, v)| (k.clone(), *v))
            .collect();
        html.push_str(&generate_bar_chart_svg(
            &chart_data,
            500,
            200,
            "Issues group by Tool",
        ));
    }

    // Top rules table
    if !stats.by_rule.is_empty() {
        html.push_str("<h3>Top Rule Violations</h3>");
        html.push_str("<table><thead><tr><th>Rule</th><th>Severity</th><th>Count</th><th>Example</th></tr></thead><tbody>");

        let mut rules: Vec<_> = stats.by_rule.values().collect();
        rules.sort_by(|a, b| b.count.cmp(&a.count));

        for rule in rules.iter().take(10) {
            let severity_badge = match rule.severity.as_str() {
                "error" => r#"<span class="badge badge-error">error</span>"#,
                "warning" => r#"<span class="badge badge-warning">warning</span>"#,
                _ => r#"<span class="badge badge-info">info</span>"#,
            };
            let message_truncated = truncate_message(&rule.example_message, 60);
            html.push_str(&format!(
                "<tr><td><code>{}</code></td><td>{}</td><td>{}</td><td>{}</td></tr>",
                html_escape(&rule.code),
                severity_badge,
                rule.count,
                html_escape(&message_truncated),
            ));
        }
        html.push_str("</tbody></table>");
    }

    // Top problematic files
    if !stats.top_files.is_empty() {
        html.push_str("<h3>Top Problematic Files</h3>");
        html.push_str("<table><thead><tr><th>File</th><th>Total</th><th>Errors</th><th>Warnings</th></tr></thead><tbody>");

        for file in stats.top_files.iter().take(10) {
            html.push_str(&format!(
                "<tr><td><code>{}</code></td><td>{}</td><td class=\"error\">{}</td><td class=\"warning\">{}</td></tr>",
                html_escape(&file.path),
                file.issue_count,
                file.error_count,
                file.warning_count,
            ));
        }
        html.push_str("</tbody></table>");
    }

    html
}

/// Generate the issues section HTML.
fn generate_issues_html(result: &RunResult) -> String {
    if result.issues.is_empty() {
        return "<p>No issues found. Great job!</p>".to_string();
    }

    let mut html = String::new();
    html.push_str("<ul class=\"issue-list\">");

    for issue in &result.issues {
        let severity_class = match issue.severity {
            Severity::Error => "error",
            Severity::Warning => "warning",
            Severity::Info => "info",
        };

        let severity_badge = match issue.severity {
            Severity::Error => r#"<span class="badge badge-error">error</span>"#,
            Severity::Warning => r#"<span class="badge badge-warning">warning</span>"#,
            Severity::Info => r#"<span class="badge badge-info">info</span>"#,
        };

        let location = format!(
            "{}:{}{}",
            issue.file_path.display(),
            issue.line,
            issue.column.map(|c| format!(":{}", c)).unwrap_or_default()
        );

        let rule_code = issue
            .code
            .as_ref()
            .map(|c| format!(" <code>[{}]</code>", html_escape(c)))
            .unwrap_or_default();

        let source = issue
            .source
            .as_ref()
            .map(|s| format!(" ({})", html_escape(s)))
            .unwrap_or_default();

        let suggestion = issue
            .suggestion
            .as_ref()
            .map(|s| {
                format!(
                    r#"<div class="issue-suggestion">💡 {}</div>"#,
                    html_escape(s)
                )
            })
            .unwrap_or_default();

        html.push_str(&format!(
            r#"<li class="issue-item {severity_class}">
            <div class="issue-header">
                <span class="issue-severity">{severity_badge}</span>
                <span class="issue-location">{location}</span>
                <span class="issue-meta">{rule_code}{source}</span>
            </div>
            <div class="issue-message">{message}</div>
            {suggestion}
        </li>"#,
            severity_class = severity_class,
            severity_badge = severity_badge,
            location = html_escape(&location),
            rule_code = rule_code,
            source = source,
            message = html_escape(&issue.message),
            suggestion = suggestion,
        ));
    }

    html.push_str("</ul>");
    html
}

/// Generate the trends section HTML.
fn generate_trends_html(trends: &TrendAnalysis) -> String {
    if trends.data_points.is_empty() {
        return "<p>Not enough historical data for trend analysis.</p>".to_string();
    }

    let mut html = String::new();

    // Trend indicator
    let trend_class = match trends.trend_direction {
        super::trends::TrendDirection::Improving => "trend-improving",
        super::trends::TrendDirection::Stable => "trend-stable",
        super::trends::TrendDirection::Degrading => "trend-degrading",
    };

    let trend_text = match trends.trend_direction {
        super::trends::TrendDirection::Improving => "↓ Improving",
        super::trends::TrendDirection::Stable => "→ Stable",
        super::trends::TrendDirection::Degrading => "↑ Degrading",
    };

    html.push_str(&format!(
        r#"<div class="stats-grid">
        <div class="stat-card">
            <div class="trend-indicator {trend_class}">{trend_text}</div>
            <div class="stat-label">Trend Direction</div>
        </div>
        <div class="stat-card">
            <div class="stat-value">{change:+.1}%</div>
            <div class="stat-label">Issue Change</div>
        </div>
        <div class="stat-card">
            <div class="stat-value">{avg:.1}</div>
            <div class="stat-label">Avg Issues/Run</div>
        </div>
        <div class="stat-card">
            <div class="stat-value">{runs}</div>
            <div class="stat-label">Runs Analyzed</div>
        </div>
    </div>"#,
        trend_class = trend_class,
        trend_text = trend_text,
        change = trends.issue_change_percentage,
        avg = trends.average_issues_per_run,
        runs = trends.data_points.len(),
    ));

    // Trend chart
    let chart_data: Vec<_> = trends
        .data_points
        .iter()
        .enumerate()
        .map(|(i, dp)| (format!("#{}", i + 1), dp.total_issues))
        .collect();

    html.push_str(&generate_trend_chart_svg(
        &chart_data,
        600,
        250,
        "Issues Over Time",
    ));

    html
}

/// Escape HTML special characters.
fn html_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&#39;")
}

/// Truncate a message to a maximum length.
fn truncate_message(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        s.to_string()
    } else {
        format!("{}", &s[..max_len.saturating_sub(1)])
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::utils::types::LintIssue;
    use std::path::PathBuf;

    #[test]
    fn test_generate_html_report_empty() {
        let result = RunResult::new();
        let options = HtmlReportOptions::default();
        let html = generate_html_report(&result, &options);

        assert!(html.contains("<!DOCTYPE html>"));
        assert!(html.contains("Linthis Report"));
        assert!(html.contains("No issues found"));
    }

    #[test]
    fn test_generate_html_report_with_issues() {
        let mut result = RunResult::new();
        result.total_files = 10;
        result.files_with_issues = 2;

        let mut issue = LintIssue::new(
            PathBuf::from("test.rs"),
            10,
            "Unused variable".to_string(),
            Severity::Warning,
        );
        issue.code = Some("W0001".to_string());
        issue.source = Some("clippy".to_string());
        result.add_issue(issue);

        let options = HtmlReportOptions::default();
        let html = generate_html_report(&result, &options);

        assert!(html.contains("test.rs:10"));
        assert!(html.contains("Unused variable"));
        assert!(html.contains("W0001"));
        assert!(html.contains("clippy"));
    }

    #[test]
    fn test_html_escape() {
        assert_eq!(html_escape("<script>"), "&lt;script&gt;");
        assert_eq!(html_escape("a & b"), "a &amp; b");
        assert_eq!(html_escape(r#"say "hi""#), "say &quot;hi&quot;");
    }

    #[test]
    fn test_truncate_message() {
        assert_eq!(truncate_message("short", 10), "short");
        assert_eq!(truncate_message("this is a long message", 10), "this is a…");
    }
}