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
//! Human-readable formatter for [`Report`] and [`FixReport`].
//!
//! The check-renderer groups violations by file path (a
//! "Repository-level" bucket leads for path-less violations,
//! everything else is alphabetical by path), emits a terminal-
//! width-aware section header for each bucket, and formats each
//! violation with a colored level sigil, the rule id, an
//! optional `fixable` tag, and the message — prefixed with
//! `line:col` when available.
//!
//! Color, glyph-set, and terminal-width decisions all come from
//! [`HumanOptions`] (see [`crate::style`]). Every styled span is
//! written as `{STYLE}…{STYLE:#}`; the CLI's `AutoStream` decides
//! whether SGR escapes reach the terminal.
use std::collections::BTreeMap;
use std::io::Write;
use std::path::Path;
use std::sync::Arc;
use alint_core::{FixReport, FixStatus, Level, Report, RuleResult, Violation};
use crate::style::{self, GlyphSet, HumanOptions, write_hyperlink};
// ---------------------------------------------------------------
// Check report
// ---------------------------------------------------------------
pub fn write_human(report: &Report, w: &mut dyn Write, opts: HumanOptions) -> std::io::Result<()> {
// Compact mode short-circuits the grouped layout entirely —
// its audience is pipes / editors / `wc -l`, not humans
// scanning output in a terminal.
if opts.compact {
return write_human_compact(report, w, &opts);
}
// All-clean banner — green check + concise line, no summary
// block. Nothing else to render.
if report.failing_rules() == 0 {
let s = style::SUCCESS;
let passing = report.passing_rules();
writeln!(
w,
"{s}{} All {passing} rule(s) passed.{s:#}",
opts.glyphs.success,
)?;
return Ok(());
}
// Bucket violations by path. `Option<Arc<Path>>` sorts `None`
// before `Some`, which we want — repository-level gaps lead.
// Cloning the Arc is an atomic refcount bump, not a path-byte
// copy.
let mut by_bucket: BTreeMap<Option<Arc<Path>>, Vec<(&RuleResult, &Violation)>> =
BTreeMap::new();
for result in &report.results {
if result.passed() {
continue;
}
for violation in &result.violations {
by_bucket
.entry(violation.path.clone())
.or_default()
.push((result, violation));
}
}
let width = opts.effective_width();
// Layout: one blank line between buckets (separates files
// from each other) and one before the summary. No blank lines
// within a bucket — visual separation between violations
// already comes from the sigil/level anchor at column 2 vs.
// the indented message continuation. Denser == easier to
// scan a repo's worth of findings on one screen.
let mut first_bucket = true;
for (bucket, items) in &by_bucket {
if !first_bucket {
writeln!(w)?;
}
first_bucket = false;
let label = bucket.as_ref().map_or_else(
|| "Repository-level".to_string(),
|p| p.display().to_string(),
);
write_section_header(w, &label, width, &opts.glyphs)?;
for (result, violation) in items {
write_violation(w, result, violation, &opts)?;
}
}
writeln!(w)?;
write_summary(w, report, &opts.glyphs)?;
Ok(())
}
/// Emit a `─── <label> ─────…` section header stretched to
/// `width` columns. Falls back gracefully when the label alone
/// exceeds the width (just emits `─── label`, no trailing fill).
fn write_section_header(
w: &mut dyn Write,
label: &str,
width: usize,
glyphs: &GlyphSet,
) -> std::io::Result<()> {
let lead = format!("{r}{r}{r} {label} ", r = glyphs.rule);
// chars().count() is a display-width approximation that
// works for ASCII + the single-column Unicode glyphs we ship.
let used = lead.chars().count();
let tail_cols = width.saturating_sub(used);
let tail: String = glyphs.rule.repeat(tail_cols);
let s = style::DIM;
writeln!(w, "{s}{lead}{tail}{s:#}")?;
Ok(())
}
/// Render a single violation block:
///
/// ```text
/// ✗ error rule-id fixable
/// 3:12 Merge-conflict markers must not be committed.
/// docs: https://…
/// ```
///
/// Caller is responsible for the blank line before this block.
fn write_violation(
w: &mut dyn Write,
result: &RuleResult,
violation: &Violation,
opts: &HumanOptions,
) -> std::io::Result<()> {
let (sigil, level_style, level_name) = level_presentation(result.level, &opts.glyphs);
let rule_style = style::RULE_ID;
// First line: indent + sigil + level + rule_id + optional `fixable` tag.
if result.is_fixable {
let fix = style::FIXABLE;
writeln!(
w,
" {level_style}{sigil} {level_name}{level_style:#} {rule_style}{}{rule_style:#} {fix}fixable{fix:#}",
result.rule_id,
)?;
} else {
writeln!(
w,
" {level_style}{sigil} {level_name}{level_style:#} {rule_style}{}{rule_style:#}",
result.rule_id,
)?;
}
// Message line. `MSG_INDENT` spaces align under the rule_id
// (col 2 indent + 1 sigil + 2 spacer + 7 level + 2 spacer = 14).
// Long messages wrap at `effective_width()` with continuation
// lines re-indented to MSG_INDENT (v0.9.19+). Wrapping is
// word-aware and falls back gracefully on long unbreakable
// tokens (URLs, hashed identifiers, etc. emit on their own
// line and let the terminal handle any overflow).
let dim = style::DIM;
let total_width = opts.effective_width();
let lines = wrap_message(&violation.message, MSG_INDENT.len(), total_width);
let (first_line, rest) = lines
.split_first()
.map_or(("", &[][..]), |(f, r)| (f.as_str(), r));
match (violation.line, violation.column) {
(Some(line), Some(col)) => {
writeln!(w, "{MSG_INDENT}{dim}{line}:{col}{dim:#} {first_line}")?;
}
(Some(line), None) => {
writeln!(w, "{MSG_INDENT}{dim}line {line}{dim:#} {first_line}")?;
}
_ => {
writeln!(w, "{MSG_INDENT}{first_line}")?;
}
}
for line in rest {
writeln!(w, "{MSG_INDENT}{line}")?;
}
// Policy URL, if present. Printed once per violation to stay
// near the relevant message (not once per rule as before —
// that hid the link below the list). When the terminal
// supports OSC 8, we wrap the URL as a clickable hyperlink.
// Suppressed entirely when `opts.show_docs` is `false`
// (`--no-docs`) so narrow terminals + screen recordings stay
// visually clean.
if opts.show_docs
&& let Some(url) = &result.policy_url
{
// Style swap on `opts.hyperlinks`: when OSC 8 is emitted the
// terminal handles link styling itself (hover underline +
// pointer cursor), so emitting our own `\e[4m` on top
// causes some renderers — notably `asciinema-player` —
// to extend the underline past the URL to the end of the
// terminal row. Drop the explicit underline in that path;
// keep it on the fallback path so non-OSC-8 terminals
// still get the visual link cue.
let docs = if opts.hyperlinks {
style::DOCS_LINKED
} else {
style::DOCS
};
write!(w, "{MSG_INDENT}{dim}docs:{dim:#} {docs}")?;
write_hyperlink(w, url, url, opts.hyperlinks)?;
writeln!(w, "{docs:#}")?;
}
Ok(())
}
/// Summary block: per-level counts, overall passing/failing/fixable
/// totals, and a `alint fix` call-to-action when anything's auto-fixable.
fn write_summary(w: &mut dyn Write, report: &Report, glyphs: &GlyphSet) -> std::io::Result<()> {
let mut errors = 0usize;
let mut warnings = 0usize;
let mut infos = 0usize;
let mut fixable_violations = 0usize;
for r in &report.results {
if r.passed() {
continue;
}
let count = r.violations.len();
if r.is_fixable {
fixable_violations += count;
}
match r.level {
Level::Error => errors += count,
Level::Warning => warnings += count,
Level::Info => infos += count,
Level::Off => {} // filtered at config load; defensive skip
}
}
let total = errors + warnings + infos;
let failing = report.failing_rules();
let passing = report.passing_rules();
let dim = style::DIM;
let plural = if total == 1 { "" } else { "s" };
writeln!(w, "{dim}Summary ({total} violation{plural}):{dim:#}")?;
// First line: per-level breakdown. Skip levels with zero count
// to keep the line short on typical runs.
let mut parts: Vec<String> = Vec::new();
if errors > 0 {
let s = style::ERROR;
parts.push(format!(
"{s}{} {errors} error{e}{s:#}",
glyphs.error,
e = if errors == 1 { "" } else { "s" }
));
}
if warnings > 0 {
let s = style::WARNING;
parts.push(format!(
"{s}{} {warnings} warning{e}{s:#}",
glyphs.warning,
e = if warnings == 1 { "" } else { "s" }
));
}
if infos > 0 {
let s = style::INFO;
parts.push(format!("{s}{} {infos} info{s:#}", glyphs.info));
}
writeln!(w, " {}", parts.join(" "))?;
// Second line: rule-level counts and fixable total.
let bullet = glyphs.bullet;
let fixable_tag = if fixable_violations > 0 {
let fix = style::FIXABLE;
format!(" {dim}{bullet}{dim:#} {fix}{fixable_violations} auto-fixable{fix:#}")
} else {
String::new()
};
writeln!(
w,
" {passing} passing {dim}{bullet}{dim:#} {failing} failing{fixable_tag}",
)?;
if fixable_violations > 0 {
writeln!(w)?;
let fix = style::FIXABLE;
writeln!(
w,
" {arrow} run {fix}`alint fix`{fix:#} to resolve {fixable_violations} fixable violation{p}.",
arrow = glyphs.arrow,
p = if fixable_violations == 1 { "" } else { "s" }
)?;
}
Ok(())
}
// ---------------------------------------------------------------
// Compact renderer
// ---------------------------------------------------------------
/// One-line-per-violation rendering, `:`-separated so editor
/// problem-matchers / `grep` / `wc -l` can consume it directly.
///
/// Format:
///
/// ```text
/// <path>:<line>:<col>: <level>: <rule-id>: <message>[ [fixable]]
/// ```
///
/// Path-less violations use the literal `<repo>` so every line
/// parses uniformly. Missing line / col are rendered as `0`.
/// Levels are color-tagged to aid visual scanning even in
/// compact form; the `AutoStream` still strips SGR escapes when
/// the sink isn't a TTY, so pipe-safe output is automatic.
fn write_human_compact(
report: &Report,
w: &mut dyn Write,
opts: &HumanOptions,
) -> std::io::Result<()> {
let mut errors = 0usize;
let mut warnings = 0usize;
let mut infos = 0usize;
let mut fixable = 0usize;
for result in &report.results {
if result.passed() {
continue;
}
for v in &result.violations {
let path = v
.path
.as_ref()
.map_or_else(|| "<repo>".to_string(), |p| p.display().to_string());
let line = v.line.unwrap_or(0);
let col = v.column.unwrap_or(0);
let (level_style, level_name) = match result.level {
Level::Error => {
errors += 1;
(style::ERROR, "error")
}
Level::Warning => {
warnings += 1;
(style::WARNING, "warning")
}
Level::Info => {
infos += 1;
(style::INFO, "info")
}
Level::Off => (style::DIM, "off"), // filtered earlier; defensive
};
if result.is_fixable {
fixable += 1;
}
let rule_style = style::RULE_ID;
let fix_tag = if result.is_fixable {
let fix = style::FIXABLE;
format!(" {fix}[fixable]{fix:#}")
} else {
String::new()
};
writeln!(
w,
"{path}:{line}:{col}: {level_style}{level_name}{level_style:#}: {rule_style}{}{rule_style:#}: {}{fix_tag}",
result.rule_id, v.message,
)?;
}
}
// Trailing summary: one line, sentence-cased, no box. Stays
// at stderr-style density so `alint check --compact | wc -l`
// still counts only violations + summary (+1).
if errors == 0 && warnings == 0 && infos == 0 {
let s = style::SUCCESS;
writeln!(w, "{s}{} all rules passed.{s:#}", opts.glyphs.success)?;
return Ok(());
}
let mut parts: Vec<String> = Vec::new();
if errors > 0 {
let s = style::ERROR;
parts.push(format!(
"{s}{errors} error{p}{s:#}",
p = if errors == 1 { "" } else { "s" }
));
}
if warnings > 0 {
let s = style::WARNING;
parts.push(format!(
"{s}{warnings} warning{p}{s:#}",
p = if warnings == 1 { "" } else { "s" }
));
}
if infos > 0 {
let s = style::INFO;
parts.push(format!("{s}{infos} info{s:#}"));
}
let mut line = parts.join(", ");
if fixable > 0 {
use std::fmt::Write as _;
let fix = style::FIXABLE;
write!(line, "; {fix}{fixable} auto-fixable{fix:#}").ok();
}
writeln!(w, "{line}.")?;
Ok(())
}
// ---------------------------------------------------------------
// Fix report
// ---------------------------------------------------------------
/// Continuation indent for `write_fix_human` wrap output.
/// 4 cols sits under the `· `/`✓ ` glyph so wrapped lines align.
const FIX_INDENT: &str = " ";
pub fn write_fix_human(
report: &FixReport,
w: &mut dyn Write,
opts: HumanOptions,
) -> std::io::Result<()> {
let dim = style::DIM;
// v0.9.20: width-aware wrap for fix output. Status-suffix prose
// ("(no fixer)", "(skipped: <reason>)") stays attached to the
// message text — wrapped together so it never lands on a line
// by itself looking orphaned.
let total_width = opts.effective_width();
for rule in &report.results {
// Fix output uses un-padded level names — it's a flat
// header per rule, no tabular alignment needed.
let (level_style, level_name) = match rule.level {
Level::Error => (style::ERROR, "error"),
Level::Warning => (style::WARNING, "warning"),
Level::Info => (style::INFO, "info"),
Level::Off => (style::DIM, "off"),
};
let rule_style = style::RULE_ID;
writeln!(
w,
"{level_style}{level_name}{level_style:#} {rule_style}[{}]{rule_style:#}:",
rule.rule_id
)?;
for item in &rule.items {
let path_prefix = item
.violation
.path
.as_ref()
.map(|p| format!("{} — ", p.display()))
.unwrap_or_default();
let (glyph, line_style_open, line_style_close, content) = match &item.status {
FixStatus::Applied(summary) => {
let s = style::SUCCESS;
(
opts.glyphs.success,
format!("{s}"),
format!("{s:#}"),
format!("{path_prefix}{summary}"),
)
}
FixStatus::Skipped(reason) => (
opts.glyphs.bullet,
format!("{dim}"),
format!("{dim:#}"),
format!(
"{path_prefix}{} (skipped: {reason})",
item.violation.message
),
),
FixStatus::Unfixable => (
opts.glyphs.bullet,
format!("{dim}"),
format!("{dim:#}"),
format!("{path_prefix}{} (no fixer)", item.violation.message),
),
};
let lines = wrap_message(&content, FIX_INDENT.len(), total_width);
let (first_line, rest) = lines
.split_first()
.map_or(("", &[][..]), |(f, r)| (f.as_str(), r));
writeln!(
w,
" {line_style_open}{glyph} {first_line}{line_style_close}"
)?;
for line in rest {
writeln!(w, "{FIX_INDENT}{line_style_open}{line}{line_style_close}")?;
}
}
}
let applied = report.applied();
let skipped = report.skipped();
let unfixable = report.unfixable();
let ok = style::SUCCESS;
writeln!(
w,
"\n{ok}{applied} applied{ok:#}, {skipped} skipped, {unfixable} unfixable."
)?;
Ok(())
}
// ---------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------
/// Aligns message text under the `rule_id` on the first line.
const MSG_INDENT: &str = " ";
/// Word-wrap `text` to fit within `total_width` columns, with
/// continuation lines indented by `indent` cols. Returns one
/// String per output line, **content only** (the caller emits the
/// indent itself before each line — keeps the styling/indent
/// concerns in one place per render path).
///
/// Whitespace-aware: breaks on ASCII spaces. Long unbreakable
/// tokens (URLs, hashed identifiers) get their own line and are
/// allowed to overflow rather than being broken mid-token.
/// Embedded newlines in `text` are honoured as paragraph breaks
/// and force a new line (each paragraph is wrapped independently).
///
/// Public since v0.9.20 so other commands' renderers (`alint
/// suggest`, `alint explain`, etc.) can apply consistent wrap
/// semantics to their own message-style output.
pub fn wrap_message(text: &str, indent: usize, total_width: usize) -> Vec<String> {
let avail = total_width.saturating_sub(indent).max(20);
let mut out: Vec<String> = Vec::new();
if text.is_empty() {
out.push(String::new());
return out;
}
for paragraph in text.split('\n') {
let mut current = String::new();
for word in paragraph.split_whitespace() {
if current.is_empty() {
current.push_str(word);
} else if current.len() + 1 + word.len() <= avail {
current.push(' ');
current.push_str(word);
} else {
out.push(std::mem::take(&mut current));
current.push_str(word);
}
}
out.push(current);
}
out
}
/// Pick the sigil, style, and padded level name for a [`Level`].
/// Level names are padded to 7 chars so the `rule_id` column aligns
/// across errors / warnings / infos.
fn level_presentation(
level: Level,
glyphs: &GlyphSet,
) -> (&'static str, anstyle::Style, &'static str) {
match level {
Level::Error => (glyphs.error, style::ERROR, "error "),
Level::Warning => (glyphs.warning, style::WARNING, "warning"),
Level::Info => (glyphs.info, style::INFO, "info "),
// `off` rules never reach the renderer — they're filtered
// at config load — but map to something sane for test use.
Level::Off => (glyphs.bullet, style::DIM, "off "),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn wrap_message_short_text_emits_one_line() {
let out = wrap_message("hello world", 14, 80);
assert_eq!(out, vec!["hello world".to_string()]);
}
#[test]
fn wrap_message_wraps_on_word_boundary_at_avail_width() {
// avail = 80 - 14 = 66 cols. Choose text that fits 65 chars
// on the first line and a tail word that pushes past.
let text = "a b c d e f g h i j k l m n o p q r s t u v w x y z aa bb cc dd ee ff gg";
let out = wrap_message(text, 14, 80);
assert!(out.len() >= 2, "expected wrap; got {out:?}");
for line in &out {
assert!(line.len() <= 66, "line over avail width: {line:?}");
}
}
#[test]
fn wrap_message_long_unbreakable_token_emits_on_own_line() {
// A long URL has no spaces; it should land on its own line
// and be allowed to overflow.
let url = "https://example.com/very/long/path/with/many/segments/that/exceeds/the/wrap";
let text = format!("see {url} for details");
let out = wrap_message(&text, 14, 60);
// First line: "see"
// Then the URL on its own line (overflowing past 46-col avail
// because no whitespace inside it)
// Then "for details"
assert!(
out.iter().any(|l| l == url),
"expected URL on its own line; got {out:?}",
);
}
#[test]
fn wrap_message_honours_explicit_newlines_as_paragraph_breaks() {
let out = wrap_message("first paragraph\nsecond paragraph", 14, 80);
assert_eq!(
out,
vec![
"first paragraph".to_string(),
"second paragraph".to_string(),
],
);
}
#[test]
fn wrap_message_empty_input_emits_one_empty_line() {
let out = wrap_message("", 14, 80);
assert_eq!(out, vec![String::new()]);
}
#[test]
fn wrap_message_tiny_width_falls_back_to_min_avail() {
// Even at width 10 (< indent 14), avail clamps to 20
// so tokens up to 20 chars fit on one line.
let out = wrap_message("twenty-char-token-ok", 14, 10);
assert_eq!(out, vec!["twenty-char-token-ok".to_string()]);
}
}