delete_path_tool.rs

  1use crate::schema::json_schema_for;
  2use anyhow::{Result, anyhow};
  3use assistant_tool::{ActionLog, Tool, ToolResult};
  4use futures::{SinkExt, StreamExt, channel::mpsc};
  5use gpui::{App, AppContext, Entity, Task};
  6use language_model::{LanguageModelRequestMessage, LanguageModelToolSchemaFormat};
  7use project::{Project, ProjectPath};
  8use schemars::JsonSchema;
  9use serde::{Deserialize, Serialize};
 10use std::sync::Arc;
 11use ui::IconName;
 12
 13#[derive(Debug, Serialize, Deserialize, JsonSchema)]
 14pub struct DeletePathToolInput {
 15    /// The path of the file or directory to delete.
 16    ///
 17    /// <example>
 18    /// If the project has the following files:
 19    ///
 20    /// - directory1/a/something.txt
 21    /// - directory2/a/things.txt
 22    /// - directory3/a/other.txt
 23    ///
 24    /// You can delete the first file by providing a path of "directory1/a/something.txt"
 25    /// </example>
 26    pub path: String,
 27}
 28
 29pub struct DeletePathTool;
 30
 31impl Tool for DeletePathTool {
 32    fn name(&self) -> String {
 33        "delete_path".into()
 34    }
 35
 36    fn needs_confirmation(&self, _: &serde_json::Value, _: &App) -> bool {
 37        true
 38    }
 39
 40    fn description(&self) -> String {
 41        include_str!("./delete_path_tool/description.md").into()
 42    }
 43
 44    fn icon(&self) -> IconName {
 45        IconName::FileDelete
 46    }
 47
 48    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
 49        json_schema_for::<DeletePathToolInput>(format)
 50    }
 51
 52    fn ui_text(&self, input: &serde_json::Value) -> String {
 53        match serde_json::from_value::<DeletePathToolInput>(input.clone()) {
 54            Ok(input) => format!("Delete “`{}`”", input.path),
 55            Err(_) => "Delete path".to_string(),
 56        }
 57    }
 58
 59    fn run(
 60        self: Arc<Self>,
 61        input: serde_json::Value,
 62        _messages: &[LanguageModelRequestMessage],
 63        project: Entity<Project>,
 64        action_log: Entity<ActionLog>,
 65        cx: &mut App,
 66    ) -> ToolResult {
 67        let path_str = match serde_json::from_value::<DeletePathToolInput>(input) {
 68            Ok(input) => input.path,
 69            Err(err) => return Task::ready(Err(anyhow!(err))).into(),
 70        };
 71        let Some(project_path) = project.read(cx).find_project_path(&path_str, cx) else {
 72            return Task::ready(Err(anyhow!(
 73                "Couldn't delete {path_str} because that path isn't in this project."
 74            )))
 75            .into();
 76        };
 77
 78        let Some(worktree) = project
 79            .read(cx)
 80            .worktree_for_id(project_path.worktree_id, cx)
 81        else {
 82            return Task::ready(Err(anyhow!(
 83                "Couldn't delete {path_str} because that path isn't in this project."
 84            )))
 85            .into();
 86        };
 87
 88        let worktree_snapshot = worktree.read(cx).snapshot();
 89        let (mut paths_tx, mut paths_rx) = mpsc::channel(256);
 90        cx.background_spawn({
 91            let project_path = project_path.clone();
 92            async move {
 93                for entry in
 94                    worktree_snapshot.traverse_from_path(true, false, false, &project_path.path)
 95                {
 96                    if !entry.path.starts_with(&project_path.path) {
 97                        break;
 98                    }
 99                    paths_tx
100                        .send(ProjectPath {
101                            worktree_id: project_path.worktree_id,
102                            path: entry.path.clone(),
103                        })
104                        .await?;
105                }
106                anyhow::Ok(())
107            }
108        })
109        .detach();
110
111        cx.spawn(async move |cx| {
112            while let Some(path) = paths_rx.next().await {
113                if let Ok(buffer) = project
114                    .update(cx, |project, cx| project.open_buffer(path, cx))?
115                    .await
116                {
117                    action_log.update(cx, |action_log, cx| {
118                        action_log.will_delete_buffer(buffer.clone(), cx)
119                    })?;
120                }
121            }
122
123            let delete = project.update(cx, |project, cx| {
124                project.delete_file(project_path, false, cx)
125            })?;
126
127            match delete {
128                Some(deletion_task) => match deletion_task.await {
129                    Ok(()) => Ok(format!("Deleted {path_str}")),
130                    Err(err) => Err(anyhow!("Failed to delete {path_str}: {err}")),
131                },
132                None => Err(anyhow!(
133                    "Couldn't delete {path_str} because that path isn't in this project."
134                )),
135            }
136        })
137        .into()
138    }
139}