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::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 project_handle = project.downgrade();
273    let diagnostic_summaries: Vec<_> = project
274        .read(cx)
275        .diagnostic_summaries(false, cx)
276        .flat_map(|(path, _, summary)| {
277            let worktree = project.read(cx).worktree_for_id(path.worktree_id, cx)?;
278            let mut path_buf = PathBuf::from(worktree.read(cx).root_name());
279            path_buf.push(&path.path);
280            Some((path, path_buf, summary))
281        })
282        .collect();
283
284    cx.spawn(|mut cx| async move {
285        let mut text = String::new();
286        if let Some(error_source) = error_source.as_ref() {
287            writeln!(text, "diagnostics: {}", error_source).unwrap();
288        } else {
289            writeln!(text, "diagnostics").unwrap();
290        }
291        let mut sections: Vec<(Range<usize>, PlaceholderType)> = Vec::new();
292
293        let mut project_summary = DiagnosticSummary::default();
294        for (project_path, path, summary) in diagnostic_summaries {
295            if let Some(path_matcher) = &options.path_matcher {
296                if !path_matcher.is_match(&path) {
297                    continue;
298                }
299            }
300
301            project_summary.error_count += summary.error_count;
302            if options.include_warnings {
303                project_summary.warning_count += summary.warning_count;
304            } else if summary.error_count == 0 {
305                continue;
306            }
307
308            let last_end = text.len();
309            let file_path = path.to_string_lossy().to_string();
310            writeln!(&mut text, "{file_path}").unwrap();
311
312            if let Some(buffer) = project_handle
313                .update(&mut cx, |project, cx| project.open_buffer(project_path, cx))?
314                .await
315                .log_err()
316            {
317                collect_buffer_diagnostics(
318                    &mut text,
319                    &mut sections,
320                    cx.read_model(&buffer, |buffer, _| buffer.snapshot())?,
321                    options.include_warnings,
322                );
323            }
324
325            sections.push((
326                last_end..text.len().saturating_sub(1),
327                PlaceholderType::File(file_path),
328            ))
329        }
330
331        // No diagnostics found
332        if sections.is_empty() {
333            return Ok(None);
334        }
335
336        sections.push((
337            0..text.len(),
338            PlaceholderType::Root(project_summary, error_source),
339        ));
340        Ok(Some((text, sections)))
341    })
342}
343
344fn collect_buffer_diagnostics(
345    text: &mut String,
346    sections: &mut Vec<(Range<usize>, PlaceholderType)>,
347    snapshot: BufferSnapshot,
348    include_warnings: bool,
349) {
350    for (_, group) in snapshot.diagnostic_groups(None) {
351        let entry = &group.entries[group.primary_ix];
352        collect_diagnostic(text, sections, entry, &snapshot, include_warnings)
353    }
354}
355
356fn collect_diagnostic(
357    text: &mut String,
358    sections: &mut Vec<(Range<usize>, PlaceholderType)>,
359    entry: &DiagnosticEntry<Anchor>,
360    snapshot: &BufferSnapshot,
361    include_warnings: bool,
362) {
363    const EXCERPT_EXPANSION_SIZE: u32 = 2;
364    const MAX_MESSAGE_LENGTH: usize = 2000;
365
366    let ty = match entry.diagnostic.severity {
367        DiagnosticSeverity::WARNING => {
368            if !include_warnings {
369                return;
370            }
371            DiagnosticType::Warning
372        }
373        DiagnosticSeverity::ERROR => DiagnosticType::Error,
374        _ => return,
375    };
376    let prev_len = text.len();
377
378    let range = entry.range.to_point(snapshot);
379    let diagnostic_row_number = range.start.row + 1;
380
381    let start_row = range.start.row.saturating_sub(EXCERPT_EXPANSION_SIZE);
382    let end_row = (range.end.row + EXCERPT_EXPANSION_SIZE).min(snapshot.max_point().row) + 1;
383    let excerpt_range =
384        Point::new(start_row, 0).to_offset(&snapshot)..Point::new(end_row, 0).to_offset(&snapshot);
385
386    text.push_str("```");
387    if let Some(language_name) = snapshot.language().map(|l| l.code_fence_block_name()) {
388        text.push_str(&language_name);
389    }
390    text.push('\n');
391
392    let mut buffer_text = String::new();
393    for chunk in snapshot.text_for_range(excerpt_range) {
394        buffer_text.push_str(chunk);
395    }
396
397    for (i, line) in buffer_text.lines().enumerate() {
398        let line_number = start_row + i as u32 + 1;
399        writeln!(text, "{}", line).unwrap();
400
401        if line_number == diagnostic_row_number {
402            text.push_str("//");
403            let prev_len = text.len();
404            write!(text, " {}: ", ty.as_str()).unwrap();
405            let padding = text.len() - prev_len;
406
407            let message = util::truncate(&entry.diagnostic.message, MAX_MESSAGE_LENGTH)
408                .replace('\n', format!("\n//{:padding$}", "").as_str());
409
410            writeln!(text, "{message}").unwrap();
411        }
412    }
413
414    writeln!(text, "```").unwrap();
415    sections.push((
416        prev_len..text.len().saturating_sub(1),
417        PlaceholderType::Diagnostic(ty, entry.diagnostic.message.clone()),
418    ))
419}
420
421#[derive(Clone)]
422pub enum PlaceholderType {
423    Root(DiagnosticSummary, Option<String>),
424    File(String),
425    Diagnostic(DiagnosticType, String),
426}
427
428#[derive(Copy, Clone)]
429pub enum DiagnosticType {
430    Warning,
431    Error,
432}
433
434impl DiagnosticType {
435    pub fn as_str(&self) -> &'static str {
436        match self {
437            DiagnosticType::Warning => "warning",
438            DiagnosticType::Error => "error",
439        }
440    }
441}