diagnostics_command.rs

  1use super::{create_label_for_command, SlashCommand, SlashCommandOutput};
  2use anyhow::{anyhow, Result};
  3use assistant_slash_command::SlashCommandOutputSection;
  4use fuzzy::{PathMatch, StringMatchCandidate};
  5use gpui::{AppContext, Model, Task, View, WeakView};
  6use language::{
  7    Anchor, BufferSnapshot, DiagnosticEntry, DiagnosticSeverity, LspAdapterDelegate,
  8    OffsetRangeExt, ToOffset,
  9};
 10use project::{DiagnosticSummary, PathMatchCandidateSet, Project};
 11use rope::Point;
 12use std::fmt::Write;
 13use std::path::{Path, PathBuf};
 14use std::{
 15    ops::Range,
 16    sync::{atomic::AtomicBool, Arc},
 17};
 18use ui::prelude::*;
 19use util::paths::PathMatcher;
 20use util::ResultExt;
 21use workspace::Workspace;
 22
 23pub(crate) struct DiagnosticsCommand;
 24
 25impl DiagnosticsCommand {
 26    fn search_paths(
 27        &self,
 28        query: String,
 29        cancellation_flag: Arc<AtomicBool>,
 30        workspace: &View<Workspace>,
 31        cx: &mut AppContext,
 32    ) -> Task<Vec<PathMatch>> {
 33        if query.is_empty() {
 34            let workspace = workspace.read(cx);
 35            let entries = workspace.recent_navigation_history(Some(10), cx);
 36            let path_prefix: Arc<str> = "".into();
 37            Task::ready(
 38                entries
 39                    .into_iter()
 40                    .map(|(entry, _)| PathMatch {
 41                        score: 0.,
 42                        positions: Vec::new(),
 43                        worktree_id: entry.worktree_id.to_usize(),
 44                        path: entry.path.clone(),
 45                        path_prefix: path_prefix.clone(),
 46                        distance_to_relative_ancestor: 0,
 47                    })
 48                    .collect(),
 49            )
 50        } else {
 51            let worktrees = workspace.read(cx).visible_worktrees(cx).collect::<Vec<_>>();
 52            let candidate_sets = worktrees
 53                .into_iter()
 54                .map(|worktree| {
 55                    let worktree = worktree.read(cx);
 56                    PathMatchCandidateSet {
 57                        snapshot: worktree.snapshot(),
 58                        include_ignored: worktree
 59                            .root_entry()
 60                            .map_or(false, |entry| entry.is_ignored),
 61                        include_root_name: true,
 62                        candidates: project::Candidates::Entries,
 63                    }
 64                })
 65                .collect::<Vec<_>>();
 66
 67            let executor = cx.background_executor().clone();
 68            cx.foreground_executor().spawn(async move {
 69                fuzzy::match_path_sets(
 70                    candidate_sets.as_slice(),
 71                    query.as_str(),
 72                    None,
 73                    false,
 74                    100,
 75                    &cancellation_flag,
 76                    executor,
 77                )
 78                .await
 79            })
 80        }
 81    }
 82}
 83
 84impl SlashCommand for DiagnosticsCommand {
 85    fn name(&self) -> String {
 86        "diagnostics".into()
 87    }
 88
 89    fn label(&self, cx: &AppContext) -> language::CodeLabel {
 90        create_label_for_command("diagnostics", &[INCLUDE_WARNINGS_ARGUMENT], cx)
 91    }
 92
 93    fn description(&self) -> String {
 94        "Insert diagnostics".into()
 95    }
 96
 97    fn menu_text(&self) -> String {
 98        "Insert Diagnostics".into()
 99    }
100
101    fn requires_argument(&self) -> bool {
102        false
103    }
104
105    fn complete_argument(
106        self: Arc<Self>,
107        query: String,
108        cancellation_flag: Arc<AtomicBool>,
109        workspace: Option<WeakView<Workspace>>,
110        cx: &mut AppContext,
111    ) -> Task<Result<Vec<String>>> {
112        let Some(workspace) = workspace.and_then(|workspace| workspace.upgrade()) else {
113            return Task::ready(Err(anyhow!("workspace was dropped")));
114        };
115        let query = query.split_whitespace().last().unwrap_or("").to_string();
116
117        let paths = self.search_paths(query.clone(), cancellation_flag.clone(), &workspace, cx);
118        let executor = cx.background_executor().clone();
119        cx.background_executor().spawn(async move {
120            let mut matches: Vec<String> = paths
121                .await
122                .into_iter()
123                .map(|path_match| {
124                    format!(
125                        "{}{}",
126                        path_match.path_prefix,
127                        path_match.path.to_string_lossy()
128                    )
129                })
130                .collect();
131
132            matches.extend(
133                fuzzy::match_strings(
134                    &Options::match_candidates_for_args(),
135                    &query,
136                    false,
137                    10,
138                    &cancellation_flag,
139                    executor,
140                )
141                .await
142                .into_iter()
143                .map(|candidate| candidate.string),
144            );
145
146            Ok(matches)
147        })
148    }
149
150    fn run(
151        self: Arc<Self>,
152        argument: Option<&str>,
153        workspace: WeakView<Workspace>,
154        _delegate: Arc<dyn LspAdapterDelegate>,
155        cx: &mut WindowContext,
156    ) -> Task<Result<SlashCommandOutput>> {
157        let Some(workspace) = workspace.upgrade() else {
158            return Task::ready(Err(anyhow!("workspace was dropped")));
159        };
160
161        let options = Options::parse(argument);
162
163        let task = collect_diagnostics(workspace.read(cx).project().clone(), options, cx);
164        cx.spawn(move |_| async move {
165            let Some((text, sections)) = task.await? else {
166                return Ok(SlashCommandOutput::default());
167            };
168
169            Ok(SlashCommandOutput {
170                text,
171                sections: sections
172                    .into_iter()
173                    .map(|(range, placeholder_type)| SlashCommandOutputSection {
174                        range,
175                        icon: match placeholder_type {
176                            PlaceholderType::Root(_, _) => IconName::ExclamationTriangle,
177                            PlaceholderType::File(_) => IconName::File,
178                            PlaceholderType::Diagnostic(DiagnosticType::Error, _) => {
179                                IconName::XCircle
180                            }
181                            PlaceholderType::Diagnostic(DiagnosticType::Warning, _) => {
182                                IconName::ExclamationTriangle
183                            }
184                        },
185                        label: match placeholder_type {
186                            PlaceholderType::Root(summary, source) => {
187                                let mut label = String::new();
188                                label.push_str("Diagnostics");
189                                if let Some(source) = source {
190                                    write!(label, " ({})", source).unwrap();
191                                }
192
193                                if summary.error_count > 0 || summary.warning_count > 0 {
194                                    label.push(':');
195
196                                    if summary.error_count > 0 {
197                                        write!(label, " {} errors", summary.error_count).unwrap();
198                                        if summary.warning_count > 0 {
199                                            label.push_str(",");
200                                        }
201                                    }
202
203                                    if summary.warning_count > 0 {
204                                        write!(label, " {} warnings", summary.warning_count)
205                                            .unwrap();
206                                    }
207                                }
208
209                                label.into()
210                            }
211                            PlaceholderType::File(file_path) => file_path.into(),
212                            PlaceholderType::Diagnostic(_, message) => message.into(),
213                        },
214                    })
215                    .collect(),
216                run_commands_in_text: false,
217            })
218        })
219    }
220}
221
222#[derive(Default)]
223struct Options {
224    include_warnings: bool,
225    path_matcher: Option<PathMatcher>,
226}
227
228const INCLUDE_WARNINGS_ARGUMENT: &str = "--include-warnings";
229
230impl Options {
231    fn parse(arguments_line: Option<&str>) -> Self {
232        arguments_line
233            .map(|arguments_line| {
234                let args = arguments_line.split_whitespace().collect::<Vec<_>>();
235                let mut include_warnings = false;
236                let mut path_matcher = None;
237                for arg in args {
238                    if arg == INCLUDE_WARNINGS_ARGUMENT {
239                        include_warnings = true;
240                    } else {
241                        path_matcher = PathMatcher::new(&[arg.to_owned()]).log_err();
242                    }
243                }
244                Self {
245                    include_warnings,
246                    path_matcher,
247                }
248            })
249            .unwrap_or_default()
250    }
251
252    fn match_candidates_for_args() -> [StringMatchCandidate; 1] {
253        [StringMatchCandidate::new(
254            0,
255            INCLUDE_WARNINGS_ARGUMENT.to_string(),
256        )]
257    }
258}
259
260fn collect_diagnostics(
261    project: Model<Project>,
262    options: Options,
263    cx: &mut AppContext,
264) -> Task<Result<Option<(String, Vec<(Range<usize>, PlaceholderType)>)>>> {
265    let error_source = if let Some(path_matcher) = &options.path_matcher {
266        debug_assert_eq!(path_matcher.sources().len(), 1);
267        Some(path_matcher.sources().first().cloned().unwrap_or_default())
268    } else {
269        None
270    };
271
272    let glob_is_exact_file_match = if let Some(path) = options
273        .path_matcher
274        .as_ref()
275        .and_then(|pm| pm.sources().first())
276    {
277        PathBuf::try_from(path)
278            .ok()
279            .and_then(|path| {
280                project.read(cx).worktrees().find_map(|worktree| {
281                    let worktree = worktree.read(cx);
282                    let worktree_root_path = Path::new(worktree.root_name());
283                    let relative_path = path.strip_prefix(worktree_root_path).ok()?;
284                    worktree.absolutize(&relative_path).ok()
285                })
286            })
287            .is_some()
288    } else {
289        false
290    };
291
292    let project_handle = project.downgrade();
293    let diagnostic_summaries: Vec<_> = project
294        .read(cx)
295        .diagnostic_summaries(false, cx)
296        .flat_map(|(path, _, summary)| {
297            let worktree = project.read(cx).worktree_for_id(path.worktree_id, cx)?;
298            let mut path_buf = PathBuf::from(worktree.read(cx).root_name());
299            path_buf.push(&path.path);
300            Some((path, path_buf, summary))
301        })
302        .collect();
303
304    cx.spawn(|mut cx| async move {
305        let mut text = String::new();
306        if let Some(error_source) = error_source.as_ref() {
307            writeln!(text, "diagnostics: {}", error_source).unwrap();
308        } else {
309            writeln!(text, "diagnostics").unwrap();
310        }
311        let mut sections: Vec<(Range<usize>, PlaceholderType)> = Vec::new();
312
313        let mut project_summary = DiagnosticSummary::default();
314        for (project_path, path, summary) in diagnostic_summaries {
315            if let Some(path_matcher) = &options.path_matcher {
316                if !path_matcher.is_match(&path) {
317                    continue;
318                }
319            }
320
321            project_summary.error_count += summary.error_count;
322            if options.include_warnings {
323                project_summary.warning_count += summary.warning_count;
324            } else if summary.error_count == 0 {
325                continue;
326            }
327
328            let last_end = text.len();
329            let file_path = path.to_string_lossy().to_string();
330            if !glob_is_exact_file_match {
331                writeln!(&mut text, "{file_path}").unwrap();
332            }
333
334            if let Some(buffer) = project_handle
335                .update(&mut cx, |project, cx| project.open_buffer(project_path, cx))?
336                .await
337                .log_err()
338            {
339                collect_buffer_diagnostics(
340                    &mut text,
341                    &mut sections,
342                    cx.read_model(&buffer, |buffer, _| buffer.snapshot())?,
343                    options.include_warnings,
344                );
345            }
346
347            if !glob_is_exact_file_match {
348                sections.push((
349                    last_end..text.len().saturating_sub(1),
350                    PlaceholderType::File(file_path),
351                ))
352            }
353        }
354
355        // No diagnostics found
356        if sections.is_empty() {
357            return Ok(None);
358        }
359
360        sections.push((
361            0..text.len(),
362            PlaceholderType::Root(project_summary, error_source),
363        ));
364        Ok(Some((text, sections)))
365    })
366}
367
368pub fn buffer_has_error_diagnostics(snapshot: &BufferSnapshot) -> bool {
369    for (_, group) in snapshot.diagnostic_groups(None) {
370        let entry = &group.entries[group.primary_ix];
371        if entry.diagnostic.severity == DiagnosticSeverity::ERROR {
372            return true;
373        }
374    }
375    false
376}
377
378pub fn write_single_file_diagnostics(
379    output: &mut String,
380    path: Option<&Path>,
381    snapshot: &BufferSnapshot,
382) -> bool {
383    if let Some(path) = path {
384        if buffer_has_error_diagnostics(&snapshot) {
385            output.push_str("/diagnostics ");
386            output.push_str(&path.to_string_lossy());
387            return true;
388        }
389    }
390    false
391}
392
393fn collect_buffer_diagnostics(
394    text: &mut String,
395    sections: &mut Vec<(Range<usize>, PlaceholderType)>,
396    snapshot: BufferSnapshot,
397    include_warnings: bool,
398) {
399    for (_, group) in snapshot.diagnostic_groups(None) {
400        let entry = &group.entries[group.primary_ix];
401        collect_diagnostic(text, sections, entry, &snapshot, include_warnings)
402    }
403}
404
405fn collect_diagnostic(
406    text: &mut String,
407    sections: &mut Vec<(Range<usize>, PlaceholderType)>,
408    entry: &DiagnosticEntry<Anchor>,
409    snapshot: &BufferSnapshot,
410    include_warnings: bool,
411) {
412    const EXCERPT_EXPANSION_SIZE: u32 = 2;
413    const MAX_MESSAGE_LENGTH: usize = 2000;
414
415    let ty = match entry.diagnostic.severity {
416        DiagnosticSeverity::WARNING => {
417            if !include_warnings {
418                return;
419            }
420            DiagnosticType::Warning
421        }
422        DiagnosticSeverity::ERROR => DiagnosticType::Error,
423        _ => return,
424    };
425    let prev_len = text.len();
426
427    let range = entry.range.to_point(snapshot);
428    let diagnostic_row_number = range.start.row + 1;
429
430    let start_row = range.start.row.saturating_sub(EXCERPT_EXPANSION_SIZE);
431    let end_row = (range.end.row + EXCERPT_EXPANSION_SIZE).min(snapshot.max_point().row) + 1;
432    let excerpt_range =
433        Point::new(start_row, 0).to_offset(&snapshot)..Point::new(end_row, 0).to_offset(&snapshot);
434
435    text.push_str("```");
436    if let Some(language_name) = snapshot.language().map(|l| l.code_fence_block_name()) {
437        text.push_str(&language_name);
438    }
439    text.push('\n');
440
441    let mut buffer_text = String::new();
442    for chunk in snapshot.text_for_range(excerpt_range) {
443        buffer_text.push_str(chunk);
444    }
445
446    for (i, line) in buffer_text.lines().enumerate() {
447        let line_number = start_row + i as u32 + 1;
448        writeln!(text, "{}", line).unwrap();
449
450        if line_number == diagnostic_row_number {
451            text.push_str("//");
452            let prev_len = text.len();
453            write!(text, " {}: ", ty.as_str()).unwrap();
454            let padding = text.len() - prev_len;
455
456            let message = util::truncate(&entry.diagnostic.message, MAX_MESSAGE_LENGTH)
457                .replace('\n', format!("\n//{:padding$}", "").as_str());
458
459            writeln!(text, "{message}").unwrap();
460        }
461    }
462
463    writeln!(text, "```").unwrap();
464    sections.push((
465        prev_len..text.len().saturating_sub(1),
466        PlaceholderType::Diagnostic(ty, entry.diagnostic.message.clone()),
467    ))
468}
469
470#[derive(Clone)]
471pub enum PlaceholderType {
472    Root(DiagnosticSummary, Option<String>),
473    File(String),
474    Diagnostic(DiagnosticType, String),
475}
476
477#[derive(Copy, Clone)]
478pub enum DiagnosticType {
479    Warning,
480    Error,
481}
482
483impl DiagnosticType {
484    pub fn as_str(&self) -> &'static str {
485        match self {
486            DiagnosticType::Warning => "warning",
487            DiagnosticType::Error => "error",
488        }
489    }
490}