poexam 0.0.10

Blazingly fast PO linter.
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
// SPDX-FileCopyrightText: 2026 Sébastien Helleu <flashcode@flashtux.org>
//
// SPDX-License-Identifier: GPL-3.0-or-later

//! Display check result.

use std::{
    collections::{BTreeMap, HashSet},
    path::{Path, PathBuf},
    time::Duration,
};

use crate::diagnostic::{Diagnostic, Severity};
use crate::sarif;
use crate::{args, rules::rule::Rules};
use crate::{checker::CheckFileResult, config::Config};

/// Display the settings used to check a file.
fn display_settings(path: &Path, config: &Config, rules: &Rules) {
    println!("Settings for file: {}", path.display());
    println!("  {config:?}");
    let rules_names = rules
        .enabled
        .iter()
        .map(|r| r.name())
        .collect::<Vec<&str>>()
        .join(", ");
    println!(
        "  Rules enabled: {}",
        if rules_names.is_empty() {
            "<none>"
        } else {
            &rules_names
        }
    );
}

/// Display diagnostics in human format.
fn display_diagnostics_human(result: &[CheckFileResult], args: &args::CheckArgs) {
    let mut diags: Vec<&Diagnostic> = result.iter().flat_map(|x| &x.diagnostics).collect();
    // Use `sort_by_cached_key`: build the sort key once per element instead of
    // once per comparison (the latter would re-allocate a `Vec<usize>` of line
    // numbers `O(N log N)` times during the sort).
    match args.sort {
        args::CheckSort::Line => {
            diags.sort_by_cached_key(|diag| {
                (
                    diag.path.clone(),
                    diag.lines
                        .iter()
                        .map(|l| l.line_number)
                        .collect::<Vec<usize>>(),
                )
            });
        }
        args::CheckSort::Message => {
            diags.sort_by_cached_key(|diag| {
                (
                    diag.lines
                        .first()
                        .map_or_else(String::new, |line| line.message.clone()),
                    diag.path.clone(),
                    diag.lines
                        .iter()
                        .map(|l| l.line_number)
                        .collect::<Vec<usize>>(),
                )
            });
        }
        args::CheckSort::Rule => {
            diags.sort_by_cached_key(|diag| {
                (
                    diag.rule,
                    diag.path.clone(),
                    diag.lines
                        .iter()
                        .map(|l| l.line_number)
                        .collect::<Vec<usize>>(),
                )
            });
        }
    }
    for diag in diags {
        println!("{diag}");
    }
}

/// Display rule statistics.
fn display_rule_stats(result: &[CheckFileResult]) {
    let mut count_rule_errors = BTreeMap::<&str, usize>::new();
    for rule in result.iter().flat_map(|x| &x.diagnostics).map(|r| r.rule) {
        *count_rule_errors.entry(rule).or_insert(0) += 1;
    }
    let mut items: Vec<_> = count_rule_errors.iter().collect();
    if items.is_empty() {
        println!("No errors found.");
        return;
    }
    items.sort_by(|a, b| b.1.cmp(a.1));
    println!("Errors by rule:");
    for (rule, count) in items {
        println!("  {rule}: {count}");
    }
}

/// Display file statistics.
fn display_file_stats(file_errors: &[(PathBuf, usize, usize, usize)]) {
    for (filename, info, warnings, errors) in file_errors {
        if errors + warnings + info == 0 {
            println!("{}: all OK!", filename.display());
        } else {
            println!(
                "{}: {} problems ({} errors, {} warnings, {} info)",
                filename.display(),
                errors + warnings + info,
                errors,
                warnings,
                info,
            );
        }
    }
}

/// Display diagnostics in JSON format.
fn display_diagnostics_json(result: &[CheckFileResult], _args: &args::CheckArgs) {
    let diags: Vec<&Diagnostic> = result.iter().flat_map(|x| &x.diagnostics).collect();
    println!("{}", serde_json::to_string(&diags).unwrap_or_default());
}

/// Display diagnostics in SARIF format.
fn display_diagnostics_sarif(result: &[CheckFileResult]) {
    let sarif_log = sarif::build_sarif(result);
    println!("{}", serde_json::to_string(&sarif_log).unwrap_or_default());
}

/// Display misspelled words.
fn display_misspelled_words(result: &[CheckFileResult], _args: &args::CheckArgs) {
    let hash_misspelled_words: HashSet<_> = result
        .iter()
        .flat_map(|x| &x.diagnostics)
        .flat_map(|d| d.misspelled_words.iter())
        .collect::<HashSet<_>>();
    let mut misspelled_words = hash_misspelled_words.iter().copied().collect::<Vec<_>>();
    misspelled_words.sort_unstable();
    for word in misspelled_words {
        println!("{word}");
    }
}

/// Display the result of the checks and return the appropriate exit code.
pub fn display_result(
    result: &[CheckFileResult],
    args: &args::CheckArgs,
    elapsed: &Duration,
) -> i32 {
    let mut files_checked = 0;
    let mut files_with_errors = 0;
    let mut count_info = 0;
    let mut count_warnings = 0;
    let mut count_errors = 0;
    let mut file_errors: Vec<(PathBuf, usize, usize, usize)> = Vec::new();
    for file in result {
        if args.show_settings && !args.quiet {
            display_settings(file.path.as_path(), &file.config, &file.rules);
        }
        let mut count_file_info = 0;
        let mut count_file_warnings = 0;
        let mut count_file_errors = 0;
        files_checked += 1;
        if !file.diagnostics.is_empty() {
            files_with_errors += 1;
            for diag in &file.diagnostics {
                match diag.severity {
                    Severity::Info => {
                        count_info += 1;
                        count_file_info += 1;
                    }
                    Severity::Warning => {
                        count_warnings += 1;
                        count_file_warnings += 1;
                    }
                    Severity::Error => {
                        count_errors += 1;
                        count_file_errors += 1;
                    }
                }
            }
        }
        if args.file_stats {
            file_errors.push((
                file.path.clone(),
                count_file_info,
                count_file_warnings,
                count_file_errors,
            ));
        }
    }
    if !args.quiet {
        match args.output {
            args::CheckOutputFormat::Human => {
                if !args.no_errors {
                    display_diagnostics_human(result, args);
                }
                if args.rule_stats {
                    display_rule_stats(result);
                }
                if args.file_stats {
                    file_errors.sort();
                    display_file_stats(&file_errors);
                }
            }
            args::CheckOutputFormat::Json => {
                if !args.no_errors {
                    display_diagnostics_json(result, args);
                }
            }
            args::CheckOutputFormat::Sarif => {
                if !args.no_errors {
                    display_diagnostics_sarif(result);
                }
            }
            args::CheckOutputFormat::Misspelled => {
                if !args.no_errors {
                    display_misspelled_words(result, args);
                }
            }
        }
    }
    if files_with_errors == 0 {
        if !args.quiet && args.output == args::CheckOutputFormat::Human {
            if files_checked > 0 {
                println!("{files_checked} files checked: all OK! [{elapsed:?}]");
            } else {
                println!("No files checked [{elapsed:?}]");
            }
        }
        0
    } else {
        if !args.quiet && args.output == args::CheckOutputFormat::Human {
            println!(
                "{files_checked} files checked: \
                {} problems \
                in {files_with_errors} files \
                ({count_errors} errors, \
                {count_warnings} warnings, \
                {count_info} info) \
                [{elapsed:?}]",
                count_errors + count_warnings + count_info
            );
        }
        if args.output == args::CheckOutputFormat::Misspelled {
            return 0;
        }
        1
    }
}

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

    fn default_check_args() -> args::CheckArgs {
        args::CheckArgs {
            files: vec![],
            show_settings: false,
            config: None,
            no_config: false,
            fuzzy: false,
            noqa: false,
            obsolete: false,
            select: None,
            ignore: None,
            path_msgfmt: None,
            path_dicts: None,
            path_words: None,
            lang_id: None,
            langs: None,
            short_factor: None,
            long_factor: None,
            severity: vec![],
            punc_ignore_ellipsis: false,
            no_errors: false,
            sort: args::CheckSort::default(),
            rule_stats: false,
            file_stats: false,
            output: args::CheckOutputFormat::default(),
            quiet: false,
        }
    }

    fn diag(rule: &'static str, severity: Severity) -> Diagnostic {
        Diagnostic::new(Path::new("test.po"), rule, severity, "msg".to_string())
    }

    fn file_result(path: &str, diagnostics: Vec<Diagnostic>) -> CheckFileResult {
        CheckFileResult {
            path: PathBuf::from(path),
            diagnostics,
            ..CheckFileResult::default()
        }
    }

    #[test]
    fn test_display_result_no_files_returns_zero() {
        let args = default_check_args();
        let code = display_result(&[], &args, &Duration::from_millis(0));
        assert_eq!(code, 0);
    }

    #[test]
    fn test_display_result_all_clean_returns_zero() {
        let args = default_check_args();
        let result = vec![file_result("a.po", vec![]), file_result("b.po", vec![])];
        let code = display_result(&result, &args, &Duration::from_millis(0));
        assert_eq!(code, 0);
    }

    #[test]
    fn test_display_result_info_diagnostic_returns_one() {
        let args = default_check_args();
        let result = vec![file_result("a.po", vec![diag("brackets", Severity::Info)])];
        let code = display_result(&result, &args, &Duration::from_millis(0));
        assert_eq!(code, 1);
    }

    #[test]
    fn test_display_result_warning_diagnostic_returns_one() {
        let args = default_check_args();
        let result = vec![file_result("a.po", vec![diag("blank", Severity::Warning)])];
        let code = display_result(&result, &args, &Duration::from_millis(0));
        assert_eq!(code, 1);
    }

    #[test]
    fn test_display_result_error_diagnostic_returns_one() {
        let args = default_check_args();
        let result = vec![file_result("a.po", vec![diag("escapes", Severity::Error)])];
        let code = display_result(&result, &args, &Duration::from_millis(0));
        assert_eq!(code, 1);
    }

    #[test]
    fn test_display_result_misspelled_mode_returns_zero_even_with_diags() {
        // Misspelled output mode is considered a "list, not a verdict" — exit 0 always.
        let mut args = default_check_args();
        args.output = args::CheckOutputFormat::Misspelled;
        let result = vec![file_result(
            "a.po",
            vec![diag("spelling-str", Severity::Info)],
        )];
        let code = display_result(&result, &args, &Duration::from_millis(0));
        assert_eq!(code, 0);
    }

    #[test]
    fn test_display_result_misspelled_mode_no_diags_returns_zero() {
        let mut args = default_check_args();
        args.output = args::CheckOutputFormat::Misspelled;
        let result = vec![file_result("a.po", vec![])];
        let code = display_result(&result, &args, &Duration::from_millis(0));
        assert_eq!(code, 0);
    }

    #[test]
    fn test_display_result_quiet_with_errors_still_returns_one() {
        let mut args = default_check_args();
        args.quiet = true;
        let result = vec![file_result("a.po", vec![diag("escapes", Severity::Error)])];
        let code = display_result(&result, &args, &Duration::from_millis(0));
        assert_eq!(code, 1);
    }

    #[test]
    fn test_display_result_no_errors_flag_does_not_change_exit_code() {
        let mut args = default_check_args();
        args.no_errors = true;
        let result = vec![file_result("a.po", vec![diag("blank", Severity::Warning)])];
        let code = display_result(&result, &args, &Duration::from_millis(0));
        assert_eq!(code, 1);
    }

    #[test]
    fn test_display_result_json_output_returns_one_on_errors() {
        let mut args = default_check_args();
        args.output = args::CheckOutputFormat::Json;
        let result = vec![file_result("a.po", vec![diag("escapes", Severity::Error)])];
        let code = display_result(&result, &args, &Duration::from_millis(0));
        assert_eq!(code, 1);
    }

    #[test]
    fn test_display_result_sarif_output_returns_one_on_errors() {
        let mut args = default_check_args();
        args.output = args::CheckOutputFormat::Sarif;
        let result = vec![file_result("a.po", vec![diag("escapes", Severity::Error)])];
        let code = display_result(&result, &args, &Duration::from_millis(0));
        assert_eq!(code, 1);
    }

    #[test]
    fn test_display_result_with_rule_and_file_stats_flags() {
        // Just verifying that turning the stats-printing flags on doesn't change the
        // exit-code logic and doesn't panic on multi-severity input.
        let mut args = default_check_args();
        args.rule_stats = true;
        args.file_stats = true;
        let result = vec![
            file_result(
                "a.po",
                vec![
                    diag("blank", Severity::Warning),
                    diag("escapes", Severity::Error),
                ],
            ),
            file_result("b.po", vec![diag("brackets", Severity::Info)]),
        ];
        let code = display_result(&result, &args, &Duration::from_millis(0));
        assert_eq!(code, 1);
    }

    #[test]
    fn test_display_result_mixed_severities_returns_one() {
        let args = default_check_args();
        let result = vec![file_result(
            "a.po",
            vec![
                diag("brackets", Severity::Info),
                diag("blank", Severity::Warning),
                diag("escapes", Severity::Error),
            ],
        )];
        let code = display_result(&result, &args, &Duration::from_millis(0));
        assert_eq!(code, 1);
    }
}