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 ui_text(&self, input: &serde_json::Value) -> String {
 50        if let Some(path) = serde_json::from_value::<DiagnosticsToolInput>(input.clone())
 51            .ok()
 52            .and_then(|input| input.path)
 53        {
 54            format!("Check diagnostics for “`{}`”", path.display())
 55        } else {
 56            "Check project diagnostics".to_string()
 57        }
 58    }
 59
 60    fn run(
 61        self: Arc<Self>,
 62        input: serde_json::Value,
 63        _messages: &[LanguageModelRequestMessage],
 64        project: Entity<Project>,
 65        _action_log: Entity<ActionLog>,
 66        cx: &mut App,
 67    ) -> Task<Result<String>> {
 68        if let Some(path) = serde_json::from_value::<DiagnosticsToolInput>(input)
 69            .ok()
 70            .and_then(|input| input.path)
 71        {
 72            let Some(project_path) = project.read(cx).find_project_path(&path, cx) else {
 73                return Task::ready(Err(anyhow!(
 74                    "Could not find path {} in project",
 75                    path.display()
 76                )));
 77            };
 78            let buffer = project.update(cx, |project, cx| project.open_buffer(project_path, cx));
 79
 80            cx.spawn(async move |cx| {
 81                let mut output = String::new();
 82                let buffer = buffer.await?;
 83                let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
 84
 85                for (_, group) in snapshot.diagnostic_groups(None) {
 86                    let entry = &group.entries[group.primary_ix];
 87                    let range = entry.range.to_point(&snapshot);
 88                    let severity = match entry.diagnostic.severity {
 89                        DiagnosticSeverity::ERROR => "error",
 90                        DiagnosticSeverity::WARNING => "warning",
 91                        _ => continue,
 92                    };
 93
 94                    writeln!(
 95                        output,
 96                        "{} at line {}: {}",
 97                        severity,
 98                        range.start.row + 1,
 99                        entry.diagnostic.message
100                    )?;
101                }
102
103                if output.is_empty() {
104                    Ok("File doesn't have errors or warnings!".to_string())
105                } else {
106                    Ok(output)
107                }
108            })
109        } else {
110            let project = project.read(cx);
111            let mut output = String::new();
112            let mut has_diagnostics = false;
113
114            for (project_path, _, summary) in project.diagnostic_summaries(true, cx) {
115                if summary.error_count > 0 || summary.warning_count > 0 {
116                    let Some(worktree) = project.worktree_for_id(project_path.worktree_id, cx)
117                    else {
118                        continue;
119                    };
120
121                    has_diagnostics = true;
122                    output.push_str(&format!(
123                        "{}: {} error(s), {} warning(s)\n",
124                        Path::new(worktree.read(cx).root_name())
125                            .join(project_path.path)
126                            .display(),
127                        summary.error_count,
128                        summary.warning_count
129                    ));
130                }
131            }
132
133            if has_diagnostics {
134                Task::ready(Ok(output))
135            } else {
136                Task::ready(Ok("No errors or warnings found in the project.".to_string()))
137            }
138        }
139    }
140}