alint-output 0.12.0

Internal: output formatters for alint reports (human, json, ...). Not a stable public API.
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
//! Markdown formatter — meant for PR comments and other rendered
//! markdown surfaces (Slack via webhook bridges, mkdocs report
//! pages, etc.). Output is GitHub-Flavored Markdown.
//!
//! Layout: an H1 banner, a one-line summary, then one H2 section
//! per file (alphabetically sorted), each containing a bulleted
//! list of violations. Path-less / cross-file violations get
//! their own "Cross-file" section after the per-file sections,
//! matching the human formatter's "Repository-level" lead bucket
//! but reordered so a reviewer sees their changed-file findings
//! first.
//!
//! Determinism: same `Report` produces byte-identical output —
//! buckets are a `BTreeMap`, violations within a bucket are
//! sorted by `(rule_id, line, column)`. Important for PR-comment
//! workflows that diff alint output across runs to detect
//! regressions.

use std::collections::BTreeMap;
use std::io::Write;
use std::path::Path;

use alint_core::{FixReport, FixStatus, Level, Report, RuleResult, Violation};

pub fn write_markdown(report: &Report, w: &mut dyn Write) -> std::io::Result<()> {
    writeln!(w, "# alint check")?;
    writeln!(w)?;

    let total = report.total_violations();
    if total == 0 {
        writeln!(w, "No violations found.")?;
        return Ok(());
    }

    write_summary_line(w, report)?;
    writeln!(w)?;

    let (by_file, cross_file) = bucket_violations(report);

    for (path, items) in &by_file {
        writeln!(
            w,
            "## `{}` ({})",
            md_inline_code(&path.display().to_string()),
            items.len()
        )?;
        writeln!(w)?;
        for (result, violation) in items {
            write_violation_bullet(w, result, violation)?;
        }
        writeln!(w)?;
    }

    if !cross_file.is_empty() {
        writeln!(w, "## Cross-file ({})", cross_file.len())?;
        writeln!(w)?;
        for (result, violation) in &cross_file {
            write_violation_bullet(w, result, violation)?;
        }
        writeln!(w)?;
    }

    Ok(())
}

pub fn write_fix_markdown(report: &FixReport, w: &mut dyn Write) -> std::io::Result<()> {
    writeln!(w, "# alint fix")?;
    writeln!(w)?;

    let applied = report.applied();
    let skipped = report.skipped();
    let unfixable = report.unfixable();

    if applied + skipped + unfixable == 0 {
        writeln!(w, "No violations found.")?;
        return Ok(());
    }

    writeln!(
        w,
        "**{applied} applied**, **{skipped} skipped**, **{unfixable} unfixable**.",
    )?;
    writeln!(w)?;

    for r in &report.results {
        if r.items.is_empty() {
            continue;
        }
        writeln!(w, "## `{}` ({})", md_inline_code(&r.rule_id), r.items.len())?;
        writeln!(w)?;
        for item in &r.items {
            let status_label = match &item.status {
                FixStatus::Applied(msg) => format!("**applied** — {}", md_escape(msg)),
                FixStatus::Skipped(msg) => format!("**skipped** — {}", md_escape(msg)),
                FixStatus::Unfixable => "**unfixable**".to_string(),
            };
            let path_part = item
                .violation
                .path
                .as_ref()
                .map(|p| format!("`{}` — ", md_inline_code(&p.display().to_string())))
                .unwrap_or_default();
            writeln!(
                w,
                "- {path_part}{status_label}: {}",
                md_escape(&item.violation.message)
            )?;
        }
        writeln!(w)?;
    }

    Ok(())
}

// ─── Helpers ───────────────────────────────────────────────────────

fn write_summary_line(w: &mut dyn Write, report: &Report) -> std::io::Result<()> {
    let total = report.total_violations();
    let (errors, warnings, infos) = level_counts(report);
    let bucket_count = file_bucket_count(report);

    let file_phrase = if bucket_count == 1 {
        "1 file".to_string()
    } else {
        format!("{bucket_count} files")
    };

    let mut breakdown: Vec<String> = Vec::new();
    if errors > 0 {
        breakdown.push(format!("{errors} error{}", plural_s(errors)));
    }
    if warnings > 0 {
        breakdown.push(format!("{warnings} warning{}", plural_s(warnings)));
    }
    if infos > 0 {
        breakdown.push(format!("{infos} info"));
    }

    if breakdown.is_empty() {
        writeln!(
            w,
            "**{total} violation{} across {file_phrase}.**",
            plural_s(total)
        )?;
    } else {
        writeln!(
            w,
            "**{total} violation{} across {file_phrase}** ({}).",
            plural_s(total),
            breakdown.join(", "),
        )?;
    }
    Ok(())
}

fn write_violation_bullet(
    w: &mut dyn Write,
    result: &RuleResult,
    violation: &Violation,
) -> std::io::Result<()> {
    let level = level_word(result.level);
    let mut loc = String::new();
    if let (Some(line), Some(col)) = (violation.line, violation.column) {
        loc = format!(" (line {line}, col {col})");
    } else if let Some(line) = violation.line {
        loc = format!(" (line {line})");
    }

    let rule_part = match &result.policy_url {
        Some(url) if !url.is_empty() => {
            format!("[`{}`]({})", md_inline_code(&result.rule_id), md_url(url))
        }
        _ => format!("`{}`", md_inline_code(&result.rule_id)),
    };

    writeln!(
        w,
        "- **{level}** {rule_part}{loc}{}",
        md_escape(&violation.message)
    )?;
    Ok(())
}

fn level_word(level: Level) -> &'static str {
    match level {
        Level::Error => "error",
        Level::Warning => "warning",
        Level::Info => "info",
        // Off rules are filtered upstream (passed() == true)
        Level::Off => "off",
    }
}

fn level_counts(report: &Report) -> (usize, usize, usize) {
    let mut e = 0;
    let mut w = 0;
    let mut i = 0;
    for r in &report.results {
        let n = r.violations.len();
        match r.level {
            Level::Error => e += n,
            Level::Warning => w += n,
            Level::Info => i += n,
            Level::Off => {}
        }
    }
    (e, w, i)
}

fn file_bucket_count(report: &Report) -> usize {
    let mut paths: std::collections::BTreeSet<Option<&Path>> = std::collections::BTreeSet::new();
    for r in &report.results {
        if r.passed() {
            continue;
        }
        for v in &r.violations {
            paths.insert(v.path.as_deref());
        }
    }
    paths.len()
}

type BucketedViolations<'a> = (
    BTreeMap<&'a Path, Vec<(&'a RuleResult, &'a Violation)>>,
    Vec<(&'a RuleResult, &'a Violation)>,
);

fn bucket_violations(report: &Report) -> BucketedViolations<'_> {
    let mut by_file: BTreeMap<&Path, Vec<(&RuleResult, &Violation)>> = BTreeMap::new();
    let mut cross_file: Vec<(&RuleResult, &Violation)> = Vec::new();
    for result in &report.results {
        if result.passed() {
            continue;
        }
        for violation in &result.violations {
            match &violation.path {
                Some(p) => by_file
                    .entry(p.as_ref())
                    .or_default()
                    .push((result, violation)),
                None => cross_file.push((result, violation)),
            }
        }
    }
    // Sort within each bucket by (rule_id, line, column) for
    // deterministic output.
    for items in by_file.values_mut() {
        items.sort_by(|a, b| sort_key(a).cmp(&sort_key(b)));
    }
    cross_file.sort_by(|a, b| sort_key(a).cmp(&sort_key(b)));
    (by_file, cross_file)
}

fn sort_key<'a>(p: &'a (&'a RuleResult, &'a Violation)) -> (&'a str, usize, usize) {
    (
        p.0.rule_id.as_ref(),
        p.1.line.unwrap_or(0),
        p.1.column.unwrap_or(0),
    )
}

fn plural_s(n: usize) -> &'static str {
    if n == 1 { "" } else { "s" }
}

/// Escape a string for safe inclusion in markdown body text.
/// Escapes the standard GFM punctuation set so a violation
/// message containing `*` / `_` / `` ` `` doesn't accidentally
/// turn the rest of the comment into bold/italic/code.
fn md_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '\\' | '`' | '*' | '_' | '{' | '}' | '[' | ']' | '<' | '>' | '(' | ')' | '#' | '+'
            | '-' | '.' | '!' | '|' | '~' => {
                out.push('\\');
                out.push(ch);
            }
            // Newlines inside bullet text break the list — collapse to a space.
            '\n' | '\r' => out.push(' '),
            _ => out.push(ch),
        }
    }
    out
}

/// Escape a string for inclusion inside a backtick code span.
/// Backticks inside code spans are tricky in `CommonMark` — the
/// canonical workaround is to switch the delimiter, but for
/// rule ids and paths the simpler choice is to substitute a
/// visually-similar character. Embedded backticks in a path are
/// vanishingly rare; embedded backticks in a rule id are
/// disallowed by the schema. Net: this only matters for
/// truly adversarial inputs.
fn md_inline_code(s: &str) -> String {
    s.replace('`', "ʼ")
}

/// Escape a URL for use in a markdown link target.
/// `CommonMark` allows most characters but parens need balancing
/// inside `(...)`. We percent-encode parens conservatively;
/// browsers handle the rest.
fn md_url(s: &str) -> String {
    s.replace('(', "%28").replace(')', "%29")
}

#[cfg(test)]
mod tests {
    use super::*;
    use alint_core::{FixItem, FixReport, FixRuleResult, FixStatus, Report, RuleResult, Violation};
    use std::path::{Path, PathBuf};

    fn render(report: &Report) -> String {
        let mut buf = Vec::new();
        write_markdown(report, &mut buf).unwrap();
        String::from_utf8(buf).unwrap()
    }

    fn render_fix(report: &FixReport) -> String {
        let mut buf = Vec::new();
        write_fix_markdown(report, &mut buf).unwrap();
        String::from_utf8(buf).unwrap()
    }

    fn rule(id: &str, level: Level, violations: Vec<Violation>) -> RuleResult {
        RuleResult {
            rule_id: id.into(),
            level,
            policy_url: None,
            violations,
            notes: Vec::new(),
            is_fixable: false,
        }
    }

    #[test]
    fn empty_report_renders_clean_banner() {
        let out = render(&Report {
            results: Vec::new(),
        });
        assert_eq!(out, "# alint check\n\nNo violations found.\n");
    }

    #[test]
    fn passing_rules_render_clean_banner() {
        let report = Report {
            results: vec![rule("ok", Level::Error, vec![])],
        };
        let out = render(&report);
        assert!(out.contains("No violations found."));
        assert!(!out.contains("##"));
    }

    #[test]
    fn single_violation_groups_under_file_heading() {
        let report = Report {
            results: vec![rule(
                "no-todo",
                Level::Error,
                vec![Violation {
                    path: Some(Path::new("src/lib.rs").into()),
                    message: "TODO marker found".into(),
                    line: Some(12),
                    column: Some(4),
                    is_note: false,
                }],
            )],
        };
        let out = render(&report);
        assert!(out.contains("**1 violation across 1 file** (1 error)."));
        assert!(out.contains("## `src/lib.rs` (1)"));
        assert!(out.contains("- **error** `no-todo` (line 12, col 4) — TODO marker found"));
    }

    #[test]
    fn multiple_files_are_alphabetically_sorted() {
        let report = Report {
            results: vec![
                rule(
                    "r-z",
                    Level::Warning,
                    vec![Violation {
                        path: Some(Path::new("zeta.rs").into()),
                        message: "z".into(),
                        line: None,
                        column: None,
                        is_note: false,
                    }],
                ),
                rule(
                    "r-a",
                    Level::Error,
                    vec![Violation {
                        path: Some(Path::new("alpha.rs").into()),
                        message: "a".into(),
                        line: None,
                        column: None,
                        is_note: false,
                    }],
                ),
            ],
        };
        let out = render(&report);
        let alpha = out.find("## `alpha.rs`").unwrap();
        let zeta = out.find("## `zeta.rs`").unwrap();
        assert!(alpha < zeta, "alpha must precede zeta");
    }

    #[test]
    fn level_counts_breakdown_in_summary() {
        let report = Report {
            results: vec![
                rule(
                    "e1",
                    Level::Error,
                    vec![Violation::new("x").with_path(PathBuf::from("a"))],
                ),
                rule(
                    "w1",
                    Level::Warning,
                    vec![
                        Violation::new("x").with_path(PathBuf::from("b")),
                        Violation::new("x").with_path(PathBuf::from("c")),
                    ],
                ),
                rule(
                    "i1",
                    Level::Info,
                    vec![Violation::new("x").with_path(PathBuf::from("d"))],
                ),
            ],
        };
        let out = render(&report);
        assert!(out.contains("**4 violations across 4 files** (1 error, 2 warnings, 1 info)."));
    }

    #[test]
    fn cross_file_violations_get_dedicated_section() {
        let report = Report {
            results: vec![rule(
                "unique-pkg",
                Level::Error,
                vec![Violation::new("duplicate package name 'pkg-001'")],
            )],
        };
        let out = render(&report);
        assert!(out.contains("## Cross-file (1)"));
        assert!(out.contains("- **error** `unique-pkg` — duplicate package name"));
    }

    #[test]
    fn cross_file_section_appears_after_per_file_sections() {
        let report = Report {
            results: vec![
                rule(
                    "no-todo",
                    Level::Error,
                    vec![Violation::new("x").with_path(PathBuf::from("a.rs"))],
                ),
                rule("unique-pkg", Level::Error, vec![Violation::new("dup")]),
            ],
        };
        let out = render(&report);
        let file_idx = out.find("## `a.rs`").unwrap();
        let cross_idx = out.find("## Cross-file").unwrap();
        assert!(file_idx < cross_idx);
    }

    #[test]
    fn policy_url_renders_as_link() {
        let report = Report {
            results: vec![RuleResult {
                rule_id: "r1".into(),
                level: Level::Error,
                policy_url: Some("https://example.com/policy".into()),
                violations: vec![Violation::new("x").with_path(PathBuf::from("a.rs"))],
                notes: Vec::new(),
                is_fixable: false,
            }],
        };
        let out = render(&report);
        assert!(out.contains("[`r1`](https://example.com/policy)"));
    }

    #[test]
    fn message_special_chars_are_escaped() {
        let report = Report {
            results: vec![rule(
                "r1",
                Level::Error,
                vec![
                    Violation::new("use **emphasis** [carefully]").with_path(PathBuf::from("a.rs")),
                ],
            )],
        };
        let out = render(&report);
        assert!(out.contains(r"use \*\*emphasis\*\* \[carefully\]"));
    }

    #[test]
    fn newline_in_message_collapses_to_space() {
        let report = Report {
            results: vec![rule(
                "r1",
                Level::Error,
                vec![Violation::new("line1\nline2").with_path(PathBuf::from("a.rs"))],
            )],
        };
        let out = render(&report);
        assert!(out.contains("line1 line2"));
        assert!(!out.contains("line1\nline2"));
    }

    #[test]
    fn line_only_no_column() {
        let report = Report {
            results: vec![rule(
                "r1",
                Level::Warning,
                vec![Violation {
                    path: Some(Path::new("a.rs").into()),
                    message: "x".into(),
                    line: Some(7),
                    column: None,
                    is_note: false,
                }],
            )],
        };
        let out = render(&report);
        assert!(out.contains("(line 7) — x"));
        assert!(!out.contains("col"));
    }

    #[test]
    fn output_is_deterministic_across_input_order() {
        let v1 = Violation {
            path: Some(Path::new("a.rs").into()),
            message: "a".into(),
            line: Some(1),
            column: Some(1),
            is_note: false,
        };
        let v2 = Violation {
            path: Some(Path::new("a.rs").into()),
            message: "b".into(),
            line: Some(2),
            column: Some(1),
            is_note: false,
        };
        let r1 = Report {
            results: vec![rule("r1", Level::Error, vec![v1.clone(), v2.clone()])],
        };
        let r2 = Report {
            results: vec![rule("r1", Level::Error, vec![v2, v1])],
        };
        assert_eq!(render(&r1), render(&r2));
    }

    #[test]
    fn fix_report_empty_renders_clean() {
        let out = render_fix(&FixReport {
            results: Vec::new(),
        });
        assert!(out.contains("No violations found."));
    }

    #[test]
    fn fix_report_groups_by_rule_with_status() {
        let report = FixReport {
            results: vec![FixRuleResult {
                rule_id: "trim".into(),
                level: Level::Warning,
                items: vec![
                    FixItem {
                        violation: Violation {
                            path: Some(Path::new("a.rs").into()),
                            message: "trailing whitespace".into(),
                            line: Some(1),
                            column: None,
                            is_note: false,
                        },
                        status: FixStatus::Applied("removed 3 trailing spaces".into()),
                    },
                    FixItem {
                        violation: Violation {
                            path: Some(Path::new("b.rs").into()),
                            message: "trailing whitespace".into(),
                            line: None,
                            column: None,
                            is_note: false,
                        },
                        status: FixStatus::Unfixable,
                    },
                ],
            }],
        };
        let out = render_fix(&report);
        assert!(out.contains("## `trim` (2)"));
        assert!(out.contains("**applied**"));
        assert!(out.contains("**unfixable**"));
        assert!(out.contains("**1 applied**, **0 skipped**, **1 unfixable**."));
    }
}