linthis 0.22.0

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
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
// 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.

//! Core types for linthis results and configuration.

use crate::Language;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

/// Issue severity levels
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    Error,
    Warning,
    Info,
}

impl std::fmt::Display for Severity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Severity::Error => write!(f, "error"),
            Severity::Warning => write!(f, "warning"),
            Severity::Info => write!(f, "info"),
        }
    }
}

/// A single lint issue found in a file
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LintIssue {
    /// Relative path to the file
    pub file_path: PathBuf,
    /// Line number (1-indexed)
    pub line: usize,
    /// Column number (1-indexed, optional)
    pub column: Option<usize>,
    /// Issue severity
    pub severity: Severity,
    /// Rule/error code (e.g., "E0001", "W0612")
    pub code: Option<String>,
    /// Human-readable description
    pub message: String,
    /// Optional fix suggestion
    pub suggestion: Option<String>,
    /// Which linter produced this issue
    pub source: Option<String>,
    /// Programming language of the file
    pub language: Option<Language>,
    /// The source code line where the issue occurs (optional)
    pub code_line: Option<String>,
    /// Context lines before the issue line (line_number, content)
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub context_before: Vec<(usize, String)>,
    /// Context lines after the issue line (line_number, content)
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub context_after: Vec<(usize, String)>,
}

impl LintIssue {
    pub fn new(file_path: PathBuf, line: usize, message: String, severity: Severity) -> Self {
        Self {
            file_path,
            line,
            column: None,
            severity,
            code: None,
            message,
            suggestion: None,
            source: None,
            language: None,
            code_line: None,
            context_before: Vec::new(),
            context_after: Vec::new(),
        }
    }

    pub fn with_column(mut self, column: usize) -> Self {
        self.column = Some(column);
        self
    }

    pub fn with_code(mut self, code: String) -> Self {
        self.code = Some(code);
        self
    }

    pub fn with_suggestion(mut self, suggestion: String) -> Self {
        self.suggestion = Some(suggestion);
        self
    }

    pub fn with_source(mut self, source: String) -> Self {
        self.source = Some(source);
        self
    }

    pub fn with_language(mut self, language: Language) -> Self {
        self.language = Some(language);
        self
    }

    pub fn with_code_line(mut self, code_line: String) -> Self {
        self.code_line = Some(code_line);
        self
    }

    pub fn with_context_before(mut self, context: Vec<(usize, String)>) -> Self {
        self.context_before = context;
        self
    }

    pub fn with_context_after(mut self, context: Vec<(usize, String)>) -> Self {
        self.context_after = context;
        self
    }
}

/// Information about an unavailable tool
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnavailableTool {
    /// The name of the tool (e.g., "clippy", "ruff")
    pub tool: String,
    /// The language this tool is for
    pub language: String,
    /// Whether this is a checker (linter) or formatter
    pub tool_type: String,
    /// Installation hint for the user
    pub install_hint: String,
    /// Whether auto-install was attempted and failed
    #[serde(default)]
    pub auto_install_failed: bool,
}

impl UnavailableTool {
    pub fn new(tool: &str, language: &str, tool_type: &str, install_hint: &str) -> Self {
        Self {
            tool: tool.to_string(),
            language: language.to_string(),
            tool_type: tool_type.to_string(),
            install_hint: install_hint.to_string(),
            auto_install_failed: false,
        }
    }

    pub fn with_auto_install_failed(mut self) -> Self {
        self.auto_install_failed = true;
        self
    }
}

/// Result of formatting a single file
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FormatResult {
    /// Relative path to the file
    pub file_path: PathBuf,
    /// Whether the file was modified
    pub changed: bool,
    /// Unified diff of changes (optional)
    pub diff: Option<String>,
    /// Error message if formatting failed
    pub error: Option<String>,
}

impl FormatResult {
    pub fn unchanged(file_path: PathBuf) -> Self {
        Self {
            file_path,
            changed: false,
            diff: None,
            error: None,
        }
    }

    pub fn changed(file_path: PathBuf) -> Self {
        Self {
            file_path,
            changed: true,
            diff: None,
            error: None,
        }
    }

    pub fn with_diff(mut self, diff: String) -> Self {
        self.diff = Some(diff);
        self
    }

    pub fn error(file_path: PathBuf, error: String) -> Self {
        Self {
            file_path,
            changed: false,
            diff: None,
            error: Some(error),
        }
    }
}

/// Run mode indicator for output messages
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RunModeKind {
    #[default]
    Both,
    CheckOnly,
    FormatOnly,
}

/// Aggregated result of a linthis run
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RunResult {
    /// Total number of files processed
    pub total_files: usize,
    /// Number of files with lint issues
    pub files_with_issues: usize,
    /// Number of files that were formatted
    pub files_formatted: usize,
    /// All lint issues found (after formatting)
    pub issues: Vec<LintIssue>,
    /// Issues found before formatting (for comparison)
    pub issues_before_format: usize,
    /// Issues fixed by formatting
    pub issues_fixed: usize,
    /// All format results
    pub format_results: Vec<FormatResult>,
    /// Total execution time in milliseconds
    pub duration_ms: u64,
    /// Exit code: 0 = success, 1 = issues found, 2 = error
    pub exit_code: i32,
    /// Run mode for appropriate output messages
    pub run_mode: RunModeKind,
    /// Tools that were not available during the run
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub unavailable_tools: Vec<UnavailableTool>,
    /// Target paths that were scanned (CLI paths before expansion)
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub target_paths: Vec<String>,
    /// SAST security scan results (present when security check is enabled)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub security: Option<crate::security::sast::SastResult>,
    /// Complexity analysis results (present when complexity check is enabled)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub complexity: Option<crate::complexity::AnalysisResult>,
    /// Which checks were actually run
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub checks_run: Vec<String>,
}

impl RunResult {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn add_issue(&mut self, issue: LintIssue) {
        self.issues.push(issue);
    }

    pub fn add_format_result(&mut self, result: FormatResult) {
        if result.changed {
            self.files_formatted += 1;
        }
        self.format_results.push(result);
    }

    /// Calculate exit code based on results
    ///
    /// Exit codes:
    /// - 0: No issues (success)
    /// - 1: Has errors
    /// - 2: Has warnings (no errors)
    /// - 3: Has info only
    /// - 4: Formatting errors occurred
    pub fn calculate_exit_code(&mut self) {
        self.calculate_exit_code_with_fail_on(&crate::config::FailOn::Warning);
    }

    /// Calculate exit code with configurable fail_on level.
    pub fn calculate_exit_code_with_fail_on(&mut self, fail_on: &crate::config::FailOn) {
        let has_format_errors = self.format_results.iter().any(|r| r.error.is_some());

        if has_format_errors {
            self.exit_code = 4;
            return;
        }

        let error_count = self
            .issues
            .iter()
            .filter(|i| i.severity == Severity::Error)
            .count();
        let warning_count = self
            .issues
            .iter()
            .filter(|i| i.severity == Severity::Warning)
            .count();
        let info_count = self
            .issues
            .iter()
            .filter(|i| i.severity == Severity::Info)
            .count();

        self.exit_code = fail_on.exit_code(error_count, warning_count, info_count);
    }

    /// Count files with issues
    pub fn count_files_with_issues(&mut self) {
        use std::collections::HashSet;
        let unique_files: HashSet<_> = self.issues.iter().map(|i| &i.file_path).collect();
        self.files_with_issues = unique_files.len();
    }

    /// Merge security and complexity findings into the issues list.
    ///
    /// Converts security `SastFinding` and complexity function metrics
    /// into `LintIssue` entries, so they can be displayed/fixed uniformly.
    pub fn merge_all_check_issues(&mut self) {
        // Merge security findings
        if let Some(ref sec) = self.security {
            for finding in &sec.findings {
                let severity = match finding.severity {
                    crate::security::Severity::Critical | crate::security::Severity::High => {
                        Severity::Error
                    }
                    crate::security::Severity::Medium => Severity::Warning,
                    _ => Severity::Info,
                };
                let mut issue = LintIssue::new(
                    finding.file_path.clone(),
                    finding.line,
                    format!("[security] {}", finding.message),
                    severity,
                );
                issue = issue.with_source(format!("security/{}", finding.source));
                issue = issue.with_code(finding.rule_id.clone());
                if let Some(ref fix) = finding.fix_suggestion {
                    issue = issue.with_suggestion(fix.clone());
                }
                self.issues.push(issue);
            }
        }

        // Merge complexity issues
        if let Some(ref cx) = self.complexity {
            let threshold = cx.thresholds.cyclomatic.good;
            let warning_threshold = cx.thresholds.cyclomatic.warning;
            let high_threshold = cx.thresholds.cyclomatic.high;
            for file in &cx.files {
                for func in &file.functions {
                    if func.metrics.cyclomatic > threshold {
                        let severity = if func.metrics.cyclomatic > high_threshold {
                            Severity::Error
                        } else if func.metrics.cyclomatic > warning_threshold {
                            Severity::Warning
                        } else {
                            Severity::Info
                        };
                        let exceeded_threshold = match severity {
                            Severity::Error => high_threshold,
                            Severity::Warning => warning_threshold,
                            _ => threshold,
                        };
                        let mut issue = LintIssue::new(
                            file.path.clone(),
                            func.start_line as usize,
                            format!(
                                "[complexity] function `{}` cyclomatic complexity {} exceeds threshold {}",
                                func.name, func.metrics.cyclomatic, exceeded_threshold,
                            ),
                            severity,
                        );
                        issue = issue.with_source("linthis-complexity".to_string());
                        issue = issue.with_suggestion(
                            "Consider refactoring into smaller functions".to_string(),
                        );
                        self.issues.push(issue);
                    }
                }
            }
        }
    }
}

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

    // ==================== Severity tests ====================

    #[test]
    fn test_severity_display_error() {
        assert_eq!(format!("{}", Severity::Error), "error");
    }

    #[test]
    fn test_severity_display_warning() {
        assert_eq!(format!("{}", Severity::Warning), "warning");
    }

    #[test]
    fn test_severity_display_info() {
        assert_eq!(format!("{}", Severity::Info), "info");
    }

    #[test]
    fn test_severity_equality() {
        assert_eq!(Severity::Error, Severity::Error);
        assert_ne!(Severity::Error, Severity::Warning);
    }

    // ==================== LintIssue tests ====================

    #[test]
    fn test_lint_issue_new() {
        let issue = LintIssue::new(
            PathBuf::from("test.cpp"),
            10,
            "Test message".to_string(),
            Severity::Warning,
        );

        assert_eq!(issue.file_path, PathBuf::from("test.cpp"));
        assert_eq!(issue.line, 10);
        assert_eq!(issue.message, "Test message");
        assert_eq!(issue.severity, Severity::Warning);
        assert!(issue.column.is_none());
        assert!(issue.code.is_none());
        assert!(issue.suggestion.is_none());
        assert!(issue.source.is_none());
        assert!(issue.language.is_none());
    }

    #[test]
    fn test_lint_issue_with_column() {
        let issue = LintIssue::new(
            PathBuf::from("test.cpp"),
            10,
            "msg".to_string(),
            Severity::Error,
        )
        .with_column(5);

        assert_eq!(issue.column, Some(5));
    }

    #[test]
    fn test_lint_issue_with_code() {
        let issue = LintIssue::new(
            PathBuf::from("test.cpp"),
            10,
            "msg".to_string(),
            Severity::Warning,
        )
        .with_code("E001".to_string());

        assert_eq!(issue.code, Some("E001".to_string()));
    }

    #[test]
    fn test_lint_issue_with_suggestion() {
        let issue = LintIssue::new(
            PathBuf::from("test.cpp"),
            10,
            "msg".to_string(),
            Severity::Info,
        )
        .with_suggestion("Use nullptr instead".to_string());

        assert_eq!(issue.suggestion, Some("Use nullptr instead".to_string()));
    }

    #[test]
    fn test_lint_issue_with_source() {
        let issue = LintIssue::new(
            PathBuf::from("test.cpp"),
            10,
            "msg".to_string(),
            Severity::Warning,
        )
        .with_source("cpplint".to_string());

        assert_eq!(issue.source, Some("cpplint".to_string()));
    }

    #[test]
    fn test_lint_issue_with_language() {
        let issue = LintIssue::new(
            PathBuf::from("test.cpp"),
            10,
            "msg".to_string(),
            Severity::Warning,
        )
        .with_language(Language::Cpp);

        assert_eq!(issue.language, Some(Language::Cpp));
    }

    #[test]
    fn test_lint_issue_builder_chaining() {
        let issue = LintIssue::new(
            PathBuf::from("test.cpp"),
            10,
            "Test error".to_string(),
            Severity::Error,
        )
        .with_column(5)
        .with_code("E001".to_string())
        .with_source("clang-tidy".to_string())
        .with_suggestion("Fix it".to_string())
        .with_language(Language::Cpp);

        assert_eq!(issue.column, Some(5));
        assert_eq!(issue.code, Some("E001".to_string()));
        assert_eq!(issue.source, Some("clang-tidy".to_string()));
        assert_eq!(issue.suggestion, Some("Fix it".to_string()));
        assert_eq!(issue.language, Some(Language::Cpp));
    }

    // ==================== FormatResult tests ====================

    #[test]
    fn test_format_result_unchanged() {
        let result = FormatResult::unchanged(PathBuf::from("test.cpp"));

        assert_eq!(result.file_path, PathBuf::from("test.cpp"));
        assert!(!result.changed);
        assert!(result.diff.is_none());
        assert!(result.error.is_none());
    }

    #[test]
    fn test_format_result_changed() {
        let result = FormatResult::changed(PathBuf::from("test.cpp"));

        assert_eq!(result.file_path, PathBuf::from("test.cpp"));
        assert!(result.changed);
        assert!(result.diff.is_none());
        assert!(result.error.is_none());
    }

    #[test]
    fn test_format_result_with_diff() {
        let result =
            FormatResult::changed(PathBuf::from("test.cpp")).with_diff("- old\n+ new".to_string());

        assert!(result.changed);
        assert_eq!(result.diff, Some("- old\n+ new".to_string()));
    }

    #[test]
    fn test_format_result_error() {
        let result = FormatResult::error(PathBuf::from("test.cpp"), "Format failed".to_string());

        assert_eq!(result.file_path, PathBuf::from("test.cpp"));
        assert!(!result.changed);
        assert!(result.diff.is_none());
        assert_eq!(result.error, Some("Format failed".to_string()));
    }

    // ==================== RunModeKind tests ====================

    #[test]
    fn test_run_mode_kind_default() {
        let mode = RunModeKind::default();
        assert_eq!(mode, RunModeKind::Both);
    }

    // ==================== RunResult tests ====================

    #[test]
    fn test_run_result_new() {
        let result = RunResult::new();

        assert_eq!(result.total_files, 0);
        assert_eq!(result.files_with_issues, 0);
        assert_eq!(result.files_formatted, 0);
        assert!(result.issues.is_empty());
        assert_eq!(result.issues_before_format, 0);
        assert_eq!(result.issues_fixed, 0);
        assert!(result.format_results.is_empty());
        assert_eq!(result.duration_ms, 0);
        assert_eq!(result.exit_code, 0);
        assert_eq!(result.run_mode, RunModeKind::Both);
    }

    #[test]
    fn test_run_result_add_issue() {
        let mut result = RunResult::new();
        let issue = LintIssue::new(
            PathBuf::from("test.cpp"),
            10,
            "Test".to_string(),
            Severity::Warning,
        );

        result.add_issue(issue);

        assert_eq!(result.issues.len(), 1);
        assert_eq!(result.issues[0].file_path, PathBuf::from("test.cpp"));
    }

    #[test]
    fn test_run_result_add_format_result_changed() {
        let mut result = RunResult::new();
        let format_result = FormatResult::changed(PathBuf::from("test.cpp"));

        result.add_format_result(format_result);

        assert_eq!(result.files_formatted, 1);
        assert_eq!(result.format_results.len(), 1);
    }

    #[test]
    fn test_run_result_add_format_result_unchanged() {
        let mut result = RunResult::new();
        let format_result = FormatResult::unchanged(PathBuf::from("test.cpp"));

        result.add_format_result(format_result);

        assert_eq!(result.files_formatted, 0);
        assert_eq!(result.format_results.len(), 1);
    }

    #[test]
    fn test_run_result_calculate_exit_code_success() {
        let mut result = RunResult::new();
        result.calculate_exit_code();
        assert_eq!(result.exit_code, 0);
    }

    #[test]
    fn test_run_result_calculate_exit_code_with_error() {
        let mut result = RunResult::new();
        result.add_issue(LintIssue::new(
            PathBuf::from("test.cpp"),
            10,
            "Error".to_string(),
            Severity::Error,
        ));

        result.calculate_exit_code();
        assert_eq!(result.exit_code, 1);
    }

    #[test]
    fn test_run_result_calculate_exit_code_with_warning() {
        let mut result = RunResult::new();
        result.add_issue(LintIssue::new(
            PathBuf::from("test.cpp"),
            10,
            "Warning".to_string(),
            Severity::Warning,
        ));

        result.calculate_exit_code();
        assert_eq!(result.exit_code, 2); // Warnings cause exit code 2
    }

    #[test]
    fn test_run_result_calculate_exit_code_format_error() {
        let mut result = RunResult::new();
        result.add_format_result(FormatResult::error(
            PathBuf::from("test.cpp"),
            "Format failed".to_string(),
        ));

        result.calculate_exit_code();
        assert_eq!(result.exit_code, 4); // Format errors cause exit code 4
    }

    #[test]
    fn test_run_result_count_files_with_issues() {
        let mut result = RunResult::new();
        result.add_issue(LintIssue::new(
            PathBuf::from("test1.cpp"),
            10,
            "Issue 1".to_string(),
            Severity::Warning,
        ));
        result.add_issue(LintIssue::new(
            PathBuf::from("test1.cpp"),
            20,
            "Issue 2".to_string(),
            Severity::Warning,
        ));
        result.add_issue(LintIssue::new(
            PathBuf::from("test2.cpp"),
            5,
            "Issue 3".to_string(),
            Severity::Error,
        ));

        result.count_files_with_issues();

        // Only 2 unique files have issues
        assert_eq!(result.files_with_issues, 2);
    }

    #[test]
    fn test_run_result_count_files_with_issues_empty() {
        let mut result = RunResult::new();
        result.count_files_with_issues();
        assert_eq!(result.files_with_issues, 0);
    }
}