mago_reporting/formatter/
rich.rs1use std::borrow::Cow;
2use std::cell::Cell;
3use std::cmp::Ordering;
4use std::collections::hash_map::Entry;
5use std::io::IsTerminal;
6use std::io::Write;
7use std::ops::Range;
8
9use codespan_reporting::diagnostic::Diagnostic;
10use codespan_reporting::diagnostic::Label;
11use codespan_reporting::diagnostic::LabelStyle;
12use codespan_reporting::diagnostic::Severity;
13use codespan_reporting::files::Error;
14use codespan_reporting::files::Files;
15use codespan_reporting::term;
16use codespan_reporting::term::Config;
17use codespan_reporting::term::DisplayStyle;
18use foldhash::HashMap;
19use termcolor::Ansi;
20use termcolor::NoColor;
21
22use mago_database::DatabaseReader;
23use mago_database::ReadDatabase;
24use mago_database::file::File;
25use mago_database::file::FileId;
26
27use crate::Annotation;
28use crate::AnnotationKind;
29use crate::Issue;
30use crate::IssueCollection;
31use crate::Level;
32use crate::error::ReportingError;
33use crate::formatter::Formatter;
34use crate::formatter::FormatterConfig;
35use crate::formatter::utils::osc8_file_hyperlink;
36use crate::formatter::utils::utf8_preserving_byte_offsets;
37
38pub(crate) struct RichFormatter;
40
41impl Formatter for RichFormatter {
42 fn format(
43 &self,
44 writer: &mut dyn Write,
45 issues: &IssueCollection,
46 database: &ReadDatabase,
47 config: &FormatterConfig,
48 ) -> Result<(), ReportingError> {
49 codespan_format_with_config(
50 writer,
51 issues,
52 database,
53 config,
54 &Config { display_style: DisplayStyle::Rich, ..Default::default() },
55 )
56 }
57}
58
59pub(super) fn codespan_format_with_config(
60 writer: &mut dyn Write,
61 issues: &IssueCollection,
62 database: &ReadDatabase,
63 config: &FormatterConfig,
64 codespan_config: &Config,
65) -> Result<(), ReportingError> {
66 let use_colors = config.color_choice.should_use_colors(std::io::stdout().is_terminal());
67 let mut ansi = Ansi::new(Vec::new());
68 let mut plain = NoColor::new(Vec::new());
69 let styled: &mut dyn term::WriteStyle = if use_colors { &mut ansi } else { &mut plain };
70
71 let editor_url = if use_colors { config.editor_url.as_deref() } else { None };
72 let files = DatabaseFiles::new(database, editor_url, issues);
73 let mut renderer = term::Renderer::new(styled, codespan_config);
74
75 let mut highest_level: Option<Level> = None;
76 let mut errors = 0;
77 let mut warnings = 0;
78 let mut notes = 0;
79 let mut help = 0;
80 let mut suggestions = 0;
81 let mut diagnostic = Diagnostic::new(Severity::Note);
82
83 for issue in crate::formatter::utils::filter_issues(issues, config, true) {
84 match issue.level {
85 Level::Note => notes += 1,
86 Level::Help => help += 1,
87 Level::Warning => warnings += 1,
88 Level::Error => errors += 1,
89 }
90
91 highest_level = Some(highest_level.map_or(issue.level, |cur| cur.max(issue.level)));
92
93 if !issue.edits.is_empty() {
94 suggestions += 1;
95 }
96
97 if editor_url.is_some() {
98 if let Some(annotation) = issue.annotations.iter().find(|a| a.is_primary()) {
99 if let Ok(file) = files.file(annotation.span.file_id) {
100 let line = file.line_number(annotation.span.start.offset) + 1;
101 let column = file.column_number(annotation.span.start.offset) + 1;
102 files.line_hint.set(Some(line));
103 files.column_hint.set(Some(column));
104 }
105 } else {
106 files.line_hint.set(None);
107 files.column_hint.set(None);
108 }
109 }
110
111 update_diagnostic(&mut diagnostic, issue);
112
113 emit_diagnostic(&mut renderer, codespan_config, &files, &diagnostic)?;
114 }
115
116 if let Some(highest_level) = highest_level {
117 let total_issues = errors + warnings + notes + help;
118 let mut message_notes = vec![];
119 if errors > 0 {
120 message_notes.push(format!("{errors} error(s)"));
121 }
122
123 if warnings > 0 {
124 message_notes.push(format!("{warnings} warning(s)"));
125 }
126
127 if notes > 0 {
128 message_notes.push(format!("{notes} note(s)"));
129 }
130
131 if help > 0 {
132 message_notes.push(format!("{help} help message(s)"));
133 }
134
135 let mut diagnostic: Diagnostic<FileId> = Diagnostic::new(highest_level.into()).with_message(format!(
136 "found {} issues: {}",
137 total_issues,
138 message_notes.join(", ")
139 ));
140
141 if suggestions > 0 {
142 diagnostic = diagnostic.with_notes(vec![format!("{} issues contain auto-fix suggestions", suggestions)]);
143 }
144
145 emit_diagnostic(&mut renderer, codespan_config, &files, &diagnostic)?;
146 }
147
148 writer.write_all(if use_colors { ansi.get_ref() } else { plain.get_ref() })?;
150
151 Ok(())
152}
153
154fn emit_diagnostic(
155 renderer: &mut term::Renderer<'_, '_>,
156 config: &Config,
157 files: &DatabaseFiles<'_>,
158 diagnostic: &Diagnostic<FileId>,
159) -> Result<(), Error> {
160 match config.display_style {
161 DisplayStyle::Rich => term::RichDiagnostic::new(diagnostic, config).render(files, renderer),
162 DisplayStyle::Medium => term::ShortDiagnostic::new(diagnostic, true).render(files, renderer),
163 DisplayStyle::Short => term::ShortDiagnostic::new(diagnostic, false).render(files, renderer),
164 }
165}
166
167struct DatabaseFiles<'db> {
168 database: &'db ReadDatabase,
169 editor_url: Option<&'db str>,
170 line_hint: Cell<Option<u32>>,
171 column_hint: Cell<Option<u32>>,
172 sources: HashMap<FileId, Cow<'db, str>>,
173 last_file: Cell<Option<&'db File>>,
174}
175
176impl<'db> DatabaseFiles<'db> {
177 fn new(database: &'db ReadDatabase, editor_url: Option<&'db str>, issues: &IssueCollection) -> Self {
178 let mut sources: HashMap<FileId, Cow<'db, str>> = HashMap::default();
179 for issue in issues.iter() {
180 for annotation in &issue.annotations {
181 let file_id = annotation.span.file_id;
182 if let Entry::Vacant(entry) = sources.entry(file_id)
183 && let Ok(file) = database.get_ref(&file_id)
184 {
185 entry.insert(utf8_preserving_byte_offsets(file.contents.as_ref()));
186 }
187 }
188 }
189
190 DatabaseFiles {
191 database,
192 editor_url,
193 line_hint: Cell::new(None),
194 column_hint: Cell::new(None),
195 sources,
196 last_file: Cell::new(None),
197 }
198 }
199
200 fn file(&self, file_id: FileId) -> Result<&'db File, Error> {
201 if let Some(file) = self.last_file.get()
202 && file.id == file_id
203 {
204 return Ok(file);
205 }
206 let file = self.database.get_ref(&file_id).map_err(|_| Error::FileMissing)?;
207 self.last_file.set(Some(file));
208 Ok(file)
209 }
210}
211
212impl<'files> Files<'files> for DatabaseFiles<'_> {
213 type FileId = FileId;
214 type Name = Cow<'files, str>;
215 type Source = &'files str;
216
217 fn name(&'files self, file_id: FileId) -> Result<Cow<'files, str>, Error> {
218 let file = self.file(file_id)?;
219 let name = String::from_utf8_lossy(&file.name);
220
221 if let (Some(template), Some(path)) = (self.editor_url, file.path.as_ref()) {
222 let abs_path = path.display().to_string();
223 let line = self.line_hint.get().unwrap_or(1);
224 let column = self.column_hint.get().unwrap_or(1);
225
226 Ok(Cow::Owned(osc8_file_hyperlink(template, &abs_path, &name, line, column, &name)))
227 } else {
228 Ok(name)
229 }
230 }
231
232 fn source(&'files self, file_id: FileId) -> Result<&'files str, Error> {
233 self.sources.get(&file_id).map(AsRef::as_ref).ok_or(Error::FileMissing)
234 }
235
236 fn line_index(&self, file_id: FileId, byte_index: usize) -> Result<usize, Error> {
237 let file = self.file(file_id)?;
238
239 Ok(file.line_number(
240 byte_index.try_into().map_err(|_| Error::IndexTooLarge { given: byte_index, max: u32::MAX as usize })?,
241 ) as usize)
242 }
243
244 fn line_range(&self, file_id: FileId, line_index: usize) -> Result<Range<usize>, Error> {
245 let file = self.file(file_id)?;
246
247 codespan_line_range(&file.lines, file.size, line_index)
248 }
249}
250
251fn update_diagnostic(diagnostic: &mut Diagnostic<FileId>, issue: &Issue) {
252 diagnostic.severity = issue.level.into();
253 diagnostic.message.clone_from(&issue.message);
254 diagnostic.code.clone_from(&issue.code);
255
256 for (index, annotation) in issue.annotations.iter().enumerate() {
257 if let Some(label) = diagnostic.labels.get_mut(index) {
258 label.style = annotation.kind.into();
259 label.file_id = annotation.span.file_id;
260 label.range = annotation.span.into();
261 if let Some(message) = &annotation.message {
262 label.message.clone_from(message);
263 } else {
264 label.message.clear();
265 }
266 } else {
267 diagnostic.labels.push(annotation.into());
268 }
269 }
270 diagnostic.labels.truncate(issue.annotations.len());
271
272 let note_count = issue.notes.len() + usize::from(issue.help.is_some()) + usize::from(issue.link.is_some());
273 diagnostic.notes.resize_with(note_count, String::new);
274 for (target, note) in diagnostic.notes.iter_mut().zip(&issue.notes) {
275 target.clone_from(note);
276 }
277 let mut remaining = diagnostic.notes[issue.notes.len()..].iter_mut();
278 for (prefix, text) in [("Help: ", issue.help.as_ref()), ("See: ", issue.link.as_ref())] {
279 if let Some(text) = text
280 && let Some(target) = remaining.next()
281 {
282 target.clear();
283 target.push_str(prefix);
284 target.push_str(text);
285 }
286 }
287}
288
289fn codespan_line_start(lines: &[u32], size: u32, line_index: usize) -> Result<usize, Error> {
290 match line_index.cmp(&lines.len()) {
291 Ordering::Less => Ok(lines.get(line_index).copied().unwrap_or(0) as usize),
295 Ordering::Equal => Ok(size as usize),
296 Ordering::Greater => Err(Error::LineTooLarge { given: line_index, max: lines.len() - 1 }),
297 }
298}
299
300fn codespan_line_range(lines: &[u32], size: u32, line_index: usize) -> Result<Range<usize>, Error> {
301 let line_start = codespan_line_start(lines, size, line_index)?;
302 let next_line_start = codespan_line_start(lines, size, line_index + 1)?;
303
304 Ok(line_start..next_line_start)
305}
306
307impl From<AnnotationKind> for LabelStyle {
308 fn from(kind: AnnotationKind) -> LabelStyle {
309 match kind {
310 AnnotationKind::Primary => LabelStyle::Primary,
311 AnnotationKind::Secondary => LabelStyle::Secondary,
312 }
313 }
314}
315
316impl From<Annotation> for Label<FileId> {
317 fn from(annotation: Annotation) -> Label<FileId> {
318 let mut label = Label::new(annotation.kind.into(), annotation.span.file_id, annotation.span);
319
320 if let Some(message) = annotation.message {
321 label.message = message;
322 }
323
324 label
325 }
326}
327
328impl From<&Annotation> for Label<FileId> {
329 fn from(annotation: &Annotation) -> Label<FileId> {
330 let mut label = Label::new(annotation.kind.into(), annotation.span.file_id, annotation.span);
331
332 if let Some(message) = &annotation.message {
333 label.message.clone_from(message);
334 }
335
336 label
337 }
338}
339
340impl From<Level> for Severity {
341 fn from(level: Level) -> Severity {
342 match level {
343 Level::Note => Severity::Note,
344 Level::Help => Severity::Help,
345 Level::Warning => Severity::Warning,
346 Level::Error => Severity::Error,
347 }
348 }
349}
350
351impl From<Issue> for Diagnostic<FileId> {
352 fn from(issue: Issue) -> Diagnostic<FileId> {
353 let mut diagnostic = Diagnostic::new(issue.level.into()).with_message(issue.message);
354
355 if let Some(code) = issue.code {
356 diagnostic.code = Some(code);
357 }
358
359 for annotation in issue.annotations {
360 diagnostic.labels.push(annotation.into());
361 }
362
363 for note in issue.notes {
364 diagnostic.notes.push(note);
365 }
366
367 if let Some(help) = issue.help {
368 diagnostic.notes.push(format!("Help: {help}"));
369 }
370
371 if let Some(link) = issue.link {
372 diagnostic.notes.push(format!("See: {link}"));
373 }
374
375 diagnostic
376 }
377}
378
379impl From<&Issue> for Diagnostic<FileId> {
380 fn from(issue: &Issue) -> Diagnostic<FileId> {
381 let mut diagnostic = Diagnostic::new(issue.level.into()).with_message(issue.message.clone());
382
383 if let Some(code) = &issue.code {
384 diagnostic.code = Some(code.clone());
385 }
386
387 for annotation in &issue.annotations {
388 diagnostic.labels.push(annotation.into());
389 }
390
391 for note in &issue.notes {
392 diagnostic.notes.push(note.clone());
393 }
394
395 if let Some(help) = &issue.help {
396 diagnostic.notes.push(format!("Help: {help}"));
397 }
398
399 if let Some(link) = &issue.link {
400 diagnostic.notes.push(format!("See: {link}"));
401 }
402
403 diagnostic
404 }
405}
406
407#[cfg(test)]
408mod tests {
409 use std::borrow::Cow;
410 use std::path::Path;
411 use std::path::PathBuf;
412
413 use codespan_reporting::files::Files;
414 use mago_database::Database;
415 use mago_database::DatabaseConfiguration;
416 use mago_database::file::File;
417 use mago_database::file::FileType;
418
419 use crate::IssueCollection;
420
421 use super::DatabaseFiles;
422
423 #[test]
424 fn editor_url_uses_the_logical_name_for_the_relative_file_placeholder() {
425 let file = File::new(
426 Cow::Borrowed(b"src/Foo.php"),
427 FileType::Host,
428 Some(PathBuf::from("/workspace/src/Foo.php")),
429 Cow::Borrowed(b"<?php\n"),
430 );
431 let file_id = file.id;
432 let configuration =
433 DatabaseConfiguration::new(Path::new("/workspace"), vec![], vec![], vec![], vec![]).into_static();
434 let database = Database::single(file, configuration).read_only();
435 let issues = IssueCollection::new();
436 let files = DatabaseFiles::new(&database, Some("editor://%rel_file%:%line%:%column%"), &issues);
437 let Ok(name) = Files::name(&files, file_id) else {
438 panic!("file should exist");
439 };
440
441 assert_eq!(name, "\x1b]8;;editor://src/Foo.php:1:1\x1b\\src/Foo.php\x1b]8;;\x1b\\",);
442 }
443}