rust-llm-tidy-cli 0.9.0

CLI for linting and tidying Rust, C#, and documentation source.
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
//! CLI output for lint diagnostics and dry-run change records.
//!
//! The CLI can report its findings either as human-readable plaintext lines
//! on stderr (the default) or as a single JSON array on stdout.
//!
//! This module owns plaintext grouping, the serializable record projection,
//! and emission. It keeps presentation separate from library execution and
//! its structured results.

use core::num::NonZeroU32;
use rust_llm_tidy::reporting::{Change, RunReport};
use rust_llm_tidy::reporting::{Diagnostic, Severity};
use serde::Serialize;
use std::borrow::Cow;
use std::io::{self, Write};
use std::path::Path;

/// Note printed once above the AI reminder group.
const AI_REMINDER_NOTE: &str = "Reminders for AI Language Models: guidance for AI agents, not required fixes.\n\
     AI reminders alone do not fail the check.\n";
/// Note printed once above the ordinary reminder group.
const REMINDER_NOTE: &str = "Reminders are prompts to consider, not required fixes. They cannot always\n\
be resolved and may remain even when the code is appropriate.\n\
Reminders alone do not fail the check.\n";

/// A serializable record for one lint finding or dry-run change.
///
/// It matches the documented JSON schema (`{ path, line, severity,
/// code, message, item_kind, item_name, title }`).
///
/// Lint findings use severity `error`, `warning`, `hint`, `reminder`, or
/// `ai_reminder`; change records use `success`. `item_name` is `null` when the
/// item is unnamed, and `title` is `null` for change records.
///
/// Text fields borrow from the projected record as [`Cow`], so a JSON run
/// allocates nothing per record besides the one `path` string.
#[derive(Serialize)]
pub(crate) struct JsonRecord<'a> {
    /// Path of the file the record was raised in.
    path: Cow<'a, str>,
    /// Optional 1-based line number where the item starts; `null` when the
    /// record has no specific line (e.g. link/table fixes).
    line: Option<NonZeroU32>,
    /// Lowercase `error`, `warning`, `hint`, `reminder`, `ai_reminder`, or
    /// `success`.
    severity: &'static str,
    /// Stable rule or operation code, e.g. "DOC001", "FIX", "REORDER", "VIS".
    code: &'static str,
    /// Human-readable description of the finding or would-be edit.
    message: Cow<'a, str>,
    /// Kind of item that produced the record, e.g. "fn".
    item_kind: Cow<'a, str>,
    /// Name of the item, or `null` when unnamed.
    item_name: Option<Cow<'a, str>>,
    /// Producer-owned title, or the raw code when absent; `null` for changes.
    title: Option<&'a str>,
}

/// Selects the CLI's lint-diagnostic output format.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub(crate) enum OutputMode {
    /// Human-readable `path:line: sev[CODE]: ...` diagnostics on stderr.
    Text,
    /// A single JSON array of all lint findings and dry-run change records on
    /// stdout.
    Json,
}

/// Render processing results before the entry point selects a failure exit code.
pub(crate) fn emit_report(report: &RunReport, json: bool) -> anyhow::Result<()> {
    let mut stderr = io::stderr().lock();
    for warning in &report.warnings {
        writeln!(stderr, "warning: {warning}")?;
    }

    if json {
        for file in &report.files {
            if let Some(error) = &file.failure {
                writeln!(stderr, "error processing {}: {error}", file.path.display())?;
            }
        }
        emit_json(report)?;
    } else {
        write_text(&mut stderr, report)?;
    }

    for failure in &report.post_process_failures {
        let action = if failure.spawn_failed {
            "failed to spawn"
        } else {
            "failed"
        };
        writeln!(
            stderr,
            "post_process `{}` {action} on {}: {}",
            failure.command,
            failure.path.display(),
            failure.message
        )?;
    }
    Ok(())
}

/// Emit every collected lint finding and dry-run change record as one JSON
/// array on stdout.
///
/// A run with neither findings nor changes emits `[]`. The document is printed
/// before any error-count or processing-failure bail so downstream consumers
/// receive all records together with the process exit code.
pub(crate) fn emit_json(report: &RunReport) -> anyhow::Result<()> {
    let count = report
        .files
        .iter()
        .map(|file| file.diagnostics.len() + file.changes.len())
        .sum();
    let mut records: Vec<JsonRecord<'_>> = Vec::with_capacity(count);
    records.extend(
        report
            .files
            .iter()
            .flat_map(|file| file.diagnostics.iter().map(|d| project_lint(&file.path, d))),
    );
    records.extend(
        report
            .files
            .iter()
            .flat_map(|file| file.changes.iter().map(|c| project_change(&file.path, c))),
    );
    // Serialization to a String is infallible for these types; propagate any
    // error defensively rather than silently truncating stdout ownership.
    let doc = serde_json::to_string(&records)?;
    // Lock once and write the document plus a trailing newline through the
    // handle so an I/O error is reported instead of silently swallowed.
    let mut out = io::stdout().lock();
    out.write_all(doc.as_bytes())?;
    out.write_all(b"\n")?;
    Ok(())
}

/// Project a single dry-run change record into its serializable form.
fn project_change<'a>(path: &Path, c: &'a Change) -> JsonRecord<'a> {
    JsonRecord {
        path: Cow::Owned(path.display().to_string()),
        line: c.line,
        severity: "success",
        code: c.code,
        message: Cow::Borrowed(c.message.as_ref()),
        item_kind: Cow::Borrowed(c.kind.as_str()),
        item_name: c.name.as_deref().map(Cow::Borrowed),
        title: None,
    }
}

/// Project a single lint finding into its serializable form.
fn project_lint<'a>(path: &Path, d: &'a Diagnostic) -> JsonRecord<'a> {
    JsonRecord {
        path: Cow::Owned(path.display().to_string()),
        line: NonZeroU32::new(d.line as u32),
        severity: match d.severity {
            Severity::Error => "error",
            Severity::Warning => "warning",
            Severity::Hint => "hint",
            Severity::Reminder => "reminder",
            Severity::AiReminder => "ai_reminder",
        },
        code: d.code,
        message: Cow::Borrowed(d.message.as_ref()),
        item_kind: Cow::Borrowed(d.item_kind.as_ref()),
        item_name: d.item_name.as_deref().map(Cow::Borrowed),
        title: Some(d.title()),
    }
}

/// Write changes, errors, warnings, and processing failures, followed by
/// separate hint, reminder, and AI reminder groups.
fn write_text(output: &mut impl Write, report: &RunReport) -> io::Result<()> {
    for file in &report.files {
        for change in &file.changes {
            writeln!(output, "{}:{change}", file.path.display())?;
        }
        for diagnostic in &file.diagnostics {
            if matches!(diagnostic.severity, Severity::Error | Severity::Warning) {
                writeln!(output, "{}:{diagnostic}", file.path.display())?;
            }
        }
        if let Some(error) = &file.failure {
            writeln!(output, "error processing {}: {error}", file.path.display())?;
        }
    }

    for severity in [Severity::Hint, Severity::Reminder, Severity::AiReminder] {
        let mut group_note_written = false;
        for file in &report.files {
            for diagnostic in &file.diagnostics {
                if diagnostic.severity != severity {
                    continue;
                }
                if !group_note_written {
                    write_group_note(output, severity)?;
                    group_note_written = true;
                }

                writeln!(output, "{}:{diagnostic}", file.path.display())?;
            }
        }
    }
    Ok(())
}

/// Write the note introducing a severity's group, before its first diagnostic.
///
/// Hints have no note: the `hint` token in each diagnostic already names the
/// group.
fn write_group_note(output: &mut impl Write, severity: Severity) -> io::Result<()> {
    match severity {
        Severity::Reminder => write!(output, "\n{REMINDER_NOTE}"),
        Severity::AiReminder => write!(output, "\n{AI_REMINDER_NOTE}"),
        _ => Ok(()),
    }
}

#[cfg(test)]
mod tests {
    use super::project_lint;
    use rstest::rstest;
    use rust_llm_tidy::reporting::{Diagnostic, FileReport, RunReport, Severity};
    use std::path::Path;

    /// Minimal finding at `line`; rendering reads only its severity and code.
    fn diagnostic(severity: Severity, line: usize) -> Diagnostic {
        Diagnostic {
            title: None,
            severity,
            code: "DOC999",
            message: "finding".into(),
            line,
            item_kind: "fn".into(),
            item_name: None,
        }
    }

    #[rstest]
    #[case::builtin("DOC001", Some("missing documentation"), "missing documentation", "")]
    #[case::symbol("SYM", Some("API reminder"), "API reminder", "API reminder: ")]
    #[case::untitled_known("DOC001", None, "DOC001", "")]
    #[case::untitled_unknown("DOC999", None, "DOC999", "")]
    #[case::untitled_symbol("SYM", None, "SYM", "")]
    fn report_should_preserve_message_and_project_producer_title(
        #[case] code: &'static str,
        #[case] title: Option<&str>,
        #[case] expected_title: &str,
        #[case] prefix: &str,
    ) {
        let report = RunReport {
            files: vec![FileReport {
                path: "input.rs".into(),
                diagnostics: vec![Diagnostic {
                    severity: Severity::Warning,
                    code,
                    title: title.map(Into::into),
                    message: "complete finding summary".into(),
                    line: 1,
                    item_kind: "fn".into(),
                    item_name: None,
                }],
                ..FileReport::default()
            }],
            ..RunReport::default()
        };
        let mut rendered = Vec::new();

        super::write_text(&mut rendered, &report).unwrap();
        let json = serde_json::to_value(project_lint(
            Path::new("input.rs"),
            &report.files[0].diagnostics[0],
        ))
        .unwrap();

        assert_eq!(json["title"], expected_title);
        assert_eq!(json["message"], "complete finding summary");
        assert!(!String::from_utf8_lossy(&rendered).contains("Reminders are prompts"));
        assert_eq!(
            String::from_utf8(rendered).unwrap(),
            format!("input.rs:1: warning[{code}]: {prefix}complete finding summary (fn)\n")
        );
    }

    #[rstest]
    #[case::error(Severity::Error, "error", 1)]
    #[case::warning(Severity::Warning, "warning", 0)]
    #[case::hint(Severity::Hint, "hint", 0)]
    #[case::reminder(Severity::Reminder, "reminder", 0)]
    #[case::ai_reminder(Severity::AiReminder, "ai_reminder", 0)]
    fn report_should_group_reminders_last_and_gate_only_errors(
        #[case] severity: Severity,
        #[case] token: &str,
        #[case] errors: usize,
    ) {
        let report = RunReport {
            files: vec![FileReport {
                path: "input.rs".into(),
                diagnostics: vec![diagnostic(Severity::Reminder, 1), diagnostic(severity, 2)],
                ..FileReport::default()
            }],
            ..RunReport::default()
        };
        let mut rendered = Vec::new();

        super::write_text(&mut rendered, &report).unwrap();
        let text = String::from_utf8(rendered).unwrap();
        let json = serde_json::to_value(project_lint(
            Path::new("input.rs"),
            &report.files[0].diagnostics[1],
        ))
        .unwrap();

        assert_eq!(report.error_count(), errors);
        assert_eq!(report.ensure_success().is_err(), errors > 0);
        assert_eq!(json["severity"], token);
        assert!(text.contains(&format!("2: {token}[DOC999]")));
        // The AI group follows the ordinary reminders, which stay in place.
        let ordinary = text.find("input.rs:1: reminder[DOC999]").unwrap();
        // Hints and non-reminder severities print before the reminder groups.
        if matches!(
            severity,
            Severity::Error | Severity::Warning | Severity::Hint
        ) {
            let preceding = text.find(&format!("input.rs:2: {token}[DOC999]")).unwrap();
            assert!(preceding < ordinary, "{text}");
        }
        let ai_heading = text.find("Reminders for AI Language Models");
        assert_eq!(
            ai_heading.is_some(),
            severity == Severity::AiReminder,
            "{text}"
        );
        if let Some(ai_heading) = ai_heading {
            assert!(ordinary < ai_heading, "{text}");
        }
        assert_eq!(text.matches("Reminders are prompts to consider").count(), 1);
        assert!(text.find("Reminders are prompts").unwrap() < ordinary);
    }

    /// One AI group covers every file, and only AI findings open it.
    #[test]
    fn report_should_group_ai_reminders_across_files() {
        let report = RunReport {
            files: vec![
                FileReport {
                    path: "a.rs".into(),
                    diagnostics: vec![diagnostic(Severity::AiReminder, 1)],
                    ..FileReport::default()
                },
                FileReport {
                    path: "b.rs".into(),
                    diagnostics: vec![
                        diagnostic(Severity::Reminder, 3),
                        diagnostic(Severity::AiReminder, 4),
                    ],
                    ..FileReport::default()
                },
            ],
            ..RunReport::default()
        };
        let mut rendered = Vec::new();

        super::write_text(&mut rendered, &report).unwrap();
        let text = String::from_utf8(rendered).unwrap();

        // Ordinary reminders first, then the single AI group in file order.
        let positions = [
            "b.rs:3: reminder[DOC999]",
            "Reminders for AI Language Models",
            "a.rs:1: ai_reminder[DOC999]",
            "b.rs:4: ai_reminder[DOC999]",
        ]
        .map(|needle| {
            text.find(needle)
                .unwrap_or_else(|| panic!("missing {needle}: {text}"))
        });

        assert!(positions.windows(2).all(|pair| pair[0] < pair[1]), "{text}");
        assert_eq!(text.matches("Reminders for AI Language Models").count(), 1);
        assert_eq!(text.matches("Reminders are prompts to consider").count(), 1);
    }

    /// Rendering groups hints last while error counts remain severity-specific.
    #[test]
    fn report_should_render_hints_last_and_count_only_errors() {
        for (name, severity, errors) in [
            ("hint_only", Severity::Hint, 0),
            ("hint_and_warning", Severity::Warning, 0),
            ("hint_and_error", Severity::Error, 1),
        ] {
            let report = RunReport {
                files: vec![
                    FileReport {
                        path: "a.rs".into(),
                        diagnostics: vec![diagnostic(Severity::Hint, 1)],
                        ..FileReport::default()
                    },
                    FileReport {
                        path: "b.rs".into(),
                        diagnostics: vec![diagnostic(severity, 2)],
                        ..FileReport::default()
                    },
                ],
                ..RunReport::default()
            };
            let mut rendered = Vec::new();

            super::write_text(&mut rendered, &report).unwrap();
            let text = String::from_utf8(rendered).unwrap();
            let lines: Vec<_> = text.lines().collect();
            let json: Vec<_> = report
                .files
                .iter()
                .flat_map(|file| {
                    file.diagnostics
                        .iter()
                        .map(|d| serde_json::to_value(project_lint(&file.path, d)).unwrap())
                })
                .collect();

            assert_eq!(report.error_count(), errors, "{name}");
            assert_eq!(report.ensure_success().is_err(), errors > 0, "{name}");
            assert_eq!(lines.len(), 2, "{name}");
            assert!(!text.contains("Reminders"), "{name}: {text}");
            if name == "hint_only" {
                assert!(lines[0].starts_with("a.rs:1: hint["));
                assert!(lines[1].starts_with("b.rs:2: hint["));
            } else {
                assert!(lines[0].starts_with("b.rs:2:"));
                assert!(lines[1].starts_with("a.rs:1: hint["));
            }
            assert_eq!(json.len(), 2);
            assert_eq!(json[0]["severity"], "hint");
        }
    }

    /// A hint finding serializes with `severity: "hint"` and the
    /// unchanged lint-record field set.
    #[test]
    fn project_lint_serializes_hint_severity() {
        let finding = Diagnostic {
            title: None,
            severity: Severity::Hint,
            code: "DOC999",
            message: String::from("consider pre-allocating the buffer"),
            line: 3,
            item_kind: String::from("fn"),
            item_name: Some(String::from("load")),
        };

        let json = serde_json::to_string(&project_lint(Path::new("src/lib.rs"), &finding)).unwrap();

        assert_eq!(
            json,
            "{\"path\":\"src/lib.rs\",\"line\":3,\"severity\":\"hint\",\
             \"code\":\"DOC999\",\"message\":\"consider pre-allocating the buffer\",\
             \"item_kind\":\"fn\",\"item_name\":\"load\",\"title\":\"DOC999\"}"
        );
    }
}