diagnostics_tool.rs

  1use anyhow::{anyhow, Result};
  2use assistant_tool::{ActionLog, Tool};
  3use gpui::{App, Entity, Task};
  4use language::{DiagnosticSeverity, OffsetRangeExt};
  5use language_model::LanguageModelRequestMessage;
  6use project::Project;
  7use schemars::JsonSchema;
  8use serde::{Deserialize, Serialize};
  9use std::{
 10    fmt::Write,
 11    path::{Path, PathBuf},
 12    sync::Arc,
 13};
 14
 15#[derive(Debug, Serialize, Deserialize, JsonSchema)]
 16pub struct DiagnosticsToolInput {
 17    /// The path to get diagnostics for. If not provided, returns a project-wide summary.
 18    ///
 19    /// This path should never be absolute, and the first component
 20    /// of the path should always be a root directory in a project.
 21    ///
 22    /// <example>
 23    /// If the project has the following root directories:
 24    ///
 25    /// - lorem
 26    /// - ipsum
 27    ///
 28    /// If you wanna access diagnostics for `dolor.txt` in `ipsum`, you should use the path `ipsum/dolor.txt`.
 29    /// </example>
 30    pub path: Option<PathBuf>,
 31}
 32
 33pub struct DiagnosticsTool;
 34
 35impl Tool for DiagnosticsTool {
 36    fn name(&self) -> String {
 37        "diagnostics".into()
 38    }
 39
 40    fn description(&self) -> String {
 41        include_str!("./diagnostics_tool/description.md").into()
 42    }
 43
 44    fn input_schema(&self) -> serde_json::Value {
 45        let schema = schemars::schema_for!(DiagnosticsToolInput);
 46        serde_json::to_value(&schema).unwrap()
 47    }
 48
 49    fn run(
 50        self: Arc<Self>,
 51        input: serde_json::Value,
 52        _messages: &[LanguageModelRequestMessage],
 53        project: Entity<Project>,
 54        _action_log: Entity<ActionLog>,
 55        cx: &mut App,
 56    ) -> Task<Result<String>> {
 57        let input = match serde_json::from_value::<DiagnosticsToolInput>(input) {
 58            Ok(input) => input,
 59            Err(err) => return Task::ready(Err(anyhow!(err))),
 60        };
 61
 62        if let Some(path) = input.path {
 63            let Some(project_path) = project.read(cx).find_project_path(&path, cx) else {
 64                return Task::ready(Err(anyhow!("Could not find path in project")));
 65            };
 66            let buffer = project.update(cx, |project, cx| project.open_buffer(project_path, cx));
 67
 68            cx.spawn(|cx| async move {
 69                let mut output = String::new();
 70                let buffer = buffer.await?;
 71                let snapshot = buffer.read_with(&cx, |buffer, _cx| buffer.snapshot())?;
 72
 73                for (_, group) in snapshot.diagnostic_groups(None) {
 74                    let entry = &group.entries[group.primary_ix];
 75                    let range = entry.range.to_point(&snapshot);
 76                    let severity = match entry.diagnostic.severity {
 77                        DiagnosticSeverity::ERROR => "error",
 78                        DiagnosticSeverity::WARNING => "warning",
 79                        _ => continue,
 80                    };
 81
 82                    writeln!(
 83                        output,
 84                        "{} at line {}: {}",
 85                        severity,
 86                        range.start.row + 1,
 87                        entry.diagnostic.message
 88                    )?;
 89                }
 90
 91                if output.is_empty() {
 92                    Ok("File doesn't have errors or warnings!".to_string())
 93                } else {
 94                    Ok(output)
 95                }
 96            })
 97        } else {
 98            let project = project.read(cx);
 99            let mut output = String::new();
100            let mut has_diagnostics = false;
101
102            for (project_path, _, summary) in project.diagnostic_summaries(true, cx) {
103                if summary.error_count > 0 || summary.warning_count > 0 {
104                    let Some(worktree) = project.worktree_for_id(project_path.worktree_id, cx)
105                    else {
106                        continue;
107                    };
108
109                    has_diagnostics = true;
110                    output.push_str(&format!(
111                        "{}: {} error(s), {} warning(s)\n",
112                        Path::new(worktree.read(cx).root_name())
113                            .join(project_path.path)
114                            .display(),
115                        summary.error_count,
116                        summary.warning_count
117                    ));
118                }
119            }
120
121            if has_diagnostics {
122                Task::ready(Ok(output))
123            } else {
124                Task::ready(Ok("No errors or warnings found in the project.".to_string()))
125            }
126        }
127    }
128}