move_path_tool.rs

  1use crate::schema::json_schema_for;
  2use action_log::ActionLog;
  3use anyhow::{Context as _, Result, anyhow};
  4use assistant_tool::{Tool, ToolResult};
  5use gpui::{AnyWindowHandle, App, AppContext, Entity, Task};
  6use language_model::{LanguageModel, LanguageModelRequest, LanguageModelToolSchemaFormat};
  7use project::Project;
  8use schemars::JsonSchema;
  9use serde::{Deserialize, Serialize};
 10use std::{path::Path, sync::Arc};
 11use ui::IconName;
 12use util::markdown::MarkdownInlineCode;
 13
 14#[derive(Debug, Serialize, Deserialize, JsonSchema)]
 15pub struct MovePathToolInput {
 16    /// The source path of the file or directory to move/rename.
 17    ///
 18    /// <example>
 19    /// If the project has the following files:
 20    ///
 21    /// - directory1/a/something.txt
 22    /// - directory2/a/things.txt
 23    /// - directory3/a/other.txt
 24    ///
 25    /// You can move the first file by providing a source_path of "directory1/a/something.txt"
 26    /// </example>
 27    pub source_path: String,
 28
 29    /// The destination path where the file or directory should be moved/renamed to.
 30    /// If the paths are the same except for the filename, then this will be a rename.
 31    ///
 32    /// <example>
 33    /// To move "directory1/a/something.txt" to "directory2/b/renamed.txt",
 34    /// provide a destination_path of "directory2/b/renamed.txt"
 35    /// </example>
 36    pub destination_path: String,
 37}
 38
 39pub struct MovePathTool;
 40
 41impl Tool for MovePathTool {
 42    fn name(&self) -> String {
 43        "move_path".into()
 44    }
 45
 46    fn needs_confirmation(&self, _: &serde_json::Value, _: &Entity<Project>, _: &App) -> bool {
 47        false
 48    }
 49
 50    fn may_perform_edits(&self) -> bool {
 51        true
 52    }
 53
 54    fn description(&self) -> String {
 55        include_str!("./move_path_tool/description.md").into()
 56    }
 57
 58    fn icon(&self) -> IconName {
 59        IconName::ArrowRightLeft
 60    }
 61
 62    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
 63        json_schema_for::<MovePathToolInput>(format)
 64    }
 65
 66    fn ui_text(&self, input: &serde_json::Value) -> String {
 67        match serde_json::from_value::<MovePathToolInput>(input.clone()) {
 68            Ok(input) => {
 69                let src = MarkdownInlineCode(&input.source_path);
 70                let dest = MarkdownInlineCode(&input.destination_path);
 71                let src_path = Path::new(&input.source_path);
 72                let dest_path = Path::new(&input.destination_path);
 73
 74                match dest_path
 75                    .file_name()
 76                    .and_then(|os_str| os_str.to_os_string().into_string().ok())
 77                {
 78                    Some(filename) if src_path.parent() == dest_path.parent() => {
 79                        let filename = MarkdownInlineCode(&filename);
 80                        format!("Rename {src} to {filename}")
 81                    }
 82                    _ => {
 83                        format!("Move {src} to {dest}")
 84                    }
 85                }
 86            }
 87            Err(_) => "Move path".to_string(),
 88        }
 89    }
 90
 91    fn run(
 92        self: Arc<Self>,
 93        input: serde_json::Value,
 94        _request: Arc<LanguageModelRequest>,
 95        project: Entity<Project>,
 96        _action_log: Entity<ActionLog>,
 97        _model: Arc<dyn LanguageModel>,
 98        _window: Option<AnyWindowHandle>,
 99        cx: &mut App,
100    ) -> ToolResult {
101        let input = match serde_json::from_value::<MovePathToolInput>(input) {
102            Ok(input) => input,
103            Err(err) => return Task::ready(Err(anyhow!(err))).into(),
104        };
105        let rename_task = project.update(cx, |project, cx| {
106            match project
107                .find_project_path(&input.source_path, cx)
108                .and_then(|project_path| project.entry_for_path(&project_path, cx))
109            {
110                Some(entity) => match project.find_project_path(&input.destination_path, cx) {
111                    Some(project_path) => project.rename_entry(entity.id, project_path, cx),
112                    None => Task::ready(Err(anyhow!(
113                        "Destination path {} was outside the project.",
114                        input.destination_path
115                    ))),
116                },
117                None => Task::ready(Err(anyhow!(
118                    "Source path {} was not found in the project.",
119                    input.source_path
120                ))),
121            }
122        });
123
124        cx.background_spawn(async move {
125            let _ = rename_task.await.with_context(|| {
126                format!("Moving {} to {}", input.source_path, input.destination_path)
127            })?;
128            Ok(format!("Moved {} to {}", input.source_path, input.destination_path).into())
129        })
130        .into()
131    }
132}